Careeroza
The Scanner Class
Reading from the Keyboard
The Scanner class in java.util reads input. Connect it to System.in (the keyboard) to read what the user types in the console.
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("Hello " + name + ", next year you will be " + (age + 1));
sc.close();
}
}Sample Run
Run it and type the values:
java Main.javaExample output
Enter your name: Nikhil Enter your age: 21 Hello Nikhil, next year you will be 22
Scanner on a String
Example
A Scanner can read from any text source, not just the keyboard. Here it reads from a String, which works exactly the same way (and lets the example run here).
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner("Nikhil\n21\n");
String name = sc.nextLine();
int age = sc.nextInt();
System.out.println("Hello " + name + ", next year you will be " + (age + 1));
}
}Output
Hello Nikhil, next year you will be 22
Tip: Close the Scanner when you are done (sc.close()). In bigger programs create one Scanner for System.in and reuse it.