Java User Input with Scanner
The Scanner class reads input from the keyboard (or from a file or a text). You import it from java.util and give it System.in.
Read text and numbers
In the examples below we send the input from the program side, so you can see the real output. When you run it, you type the input in the terminal.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Name: ");
String name = sc.nextLine();
System.out.print("Age: ");
int age = sc.nextInt();
System.out.print("Marks: ");
double marks = sc.nextDouble();
System.out.println();
System.out.println(name + ", " + age + ", " + marks);
sc.close();
}
}
Output
Name: Age: Marks:
Riya, 21, 88.5
In the output the three questions are on one line, because here the input is sent by the program and not typed by a person. In a real terminal, every answer you type comes on its own line.
Scanner methods
| Method | Reads |
|---|---|
| nextLine() | A full line of text |
| next() | One word (until a space) |
| nextInt() | An int |
| nextDouble() | A double |
| nextBoolean() | true or false |
| nextLong() | A long |
| hasNextInt(), hasNextLine() | Check if there is more input of that type |
The newline problem
nextInt() reads the number but leaves the Enter key (the new line) in the input. A nextLine() after it then reads an empty text. The fix: call nextLine() once to clear the line.
import java.util.Scanner;
public class Problem {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
String name = sc.nextLine(); // reads the rest of the first line: empty
System.out.println("[" + name + "]");
}
}
Output
[]
import java.util.Scanner;
public class Fixed {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
sc.nextLine(); // clear the new line
String name = sc.nextLine();
System.out.println(age + " " + name);
}
}
Output
25 Riya Sharma
Check the input before reading
import java.util.Scanner;
public class Check {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()) {
System.out.println("Number: " + sc.nextInt());
} else {
System.out.println("That is not a number: " + sc.next());
}
}
}
Output
That is not a number: abc
Read until the end
import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int total = 0;
while (sc.hasNextInt()) {
total += sc.nextInt();
}
System.out.println("Total: " + total);
}
}
Output
Total: 60
Note:
If the user types text when you call nextInt(), Java throws an InputMismatchException. Use hasNextInt() first. Next: Java Math Class.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |