How to Read the Input Value in Java
Every learning Java developer knows about the "System.out.println" command as a way to print a string of text to the terminal, if only because every introductory Java lesson begins with the traditional, "Hello World!" command. They may also notice that there is a "System.in" class, but it lacks an easy-to-use "readln" command. Reading input values is slightly trickier, but it can be made easy with the help of the "Scanner" class in the Java standard library.
Instructions
-
-
1
Open "Netbeans" or another Java Integrated Development Environment (IDE). You can also use any text editor, though these instructions will assume you can either use the Netbeans tools or know how to duplicate them on the command line.
-
2
Click "File" and "New class." Name it "ReadTester."
-
-
3
Type "psvm." This will expand to a valid main method.
-
4
Type the following within the main method:
Scanner scanner = new Scanner(System.in);
System.out.println("What is your name?");
String name = scanner.nextLine();
System.out.println("Hello " + name);
-
1
Tips & Warnings
The Scanner class isn't just good for reading lines of text. It also contains methods for automatically parsing data values and even for determining whether the next value entered can be interpreted as a certain data type without error.