-
Notifications
You must be signed in to change notification settings - Fork 4
Reading Input in Java Using Scanner
Ramesh Fadatare edited this page Jul 12, 2019
·
1 revision
The Java example shows how to read a value from a console.
import java.util.Scanner;
public class ReadLine {
public static void main(String[] args) {
System.out.print("Write your name:");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println("Hello " + name);
}
}A prompt is shown on the terminal window. The user writes his name on the terminal and the value is read and printed back to the terminal.
Output:
java com.sourcecodeexamples.ReadLine
Write your name: Ramesh
Hello Ramesh
In the example above, we used the nextLine() method, which is used to read Strings. To read other types, look at below Scanner class methods:
- nextBoolean() - Reads a boolean value from the user
- nextByte() - Reads a byte value from the user
- nextDouble() - Reads a double value from the user
- nextFloat() - Reads a float value from the user
- nextInt() - Reads a int value from the user
- nextLine() - Reads a String value from the user
- nextLong() - Reads a long value from the user
- nextShort() - Reads a short value from the user