Java User Input (Scanner)

Java User Input (Scanner)

To take input from the user in Java, we use the Scanner class, which is part of the java.util package.

Before using it, you must import it:

import java.util.Scanner;

Then create a Scanner object:

Scanner input = new Scanner(System.in);

Example: Taking a String Input

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.println(“Enter your name:”);
String name = sc.nextLine();

System.out.println(“Hello, “ + name);
}
}

✔ Output:

Enter your name:
John
Hello, John

 Input Methods in Scanner

Method Use
nextLine() Reads whole line (including spaces)
next() Reads a single word
nextInt() Reads an integer
nextDouble() Reads a decimal number
nextFloat() Reads a float
nextBoolean() Reads a boolean (true/false)
nextLong() Reads a long value

 Example: Number Input

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print(“Enter your age: “);
int age = sc.nextInt();

System.out.println(“You are “ + age + ” years old.”);
}
}


 Taking Multiple Inputs

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print(“Enter your name: “);
String name = sc.nextLine();

System.out.print(“Enter your age: “);
int age = sc.nextInt();

System.out.println(“Name: “ + name + “, Age: “ + age);
}
}


⚠️ Important: Using nextLine() After nextInt()

When mixing numeric and string inputs, nextInt() leaves a newline (\n) in the buffer.

So after using nextInt(), add one nextLine():

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print(“Enter age: “);
int age = sc.nextInt();
sc.nextLine(); // consume leftover newline

System.out.print(“Enter city: “);
String city = sc.nextLine();

System.out.println(“Age: “ + age + “, City: “ + city);
}
}


 Example: Simple Calculator using User Input

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print(“Enter first number: “);
int a = sc.nextInt();

System.out.print(“Enter second number: “);
int b = sc.nextInt();

System.out.println(“Sum = “ + (a + b));
}
}


🏁 Summary

✔ Use Scanner to take input from the user
✔ Different methods exist for different data types
✔ Use nextLine() after nextInt() (or similar) to avoid input issues

You may also like...