How to Read Java Input
When creating an application, Java programmers often need to be able to read input from users. For example, this can be a request for confirmation or reading of additional data to be processed. The Input read generally comes from either the screen or from a file. Regardless of the sources, the Java programming language provides a common Scanner class that allows you to process the input read as a series of tokens.
Instructions
-
-
1
Click on the "Start" button and type "Notepad" on the application search box. Click "Notepad" from the resulting list of programs that appears. Enter the following code in the new Notepad window:
public class ScanXan {
public static void main(String[] args) throws IOException {
}
}
-
2
Type "import java.util.Scanner;" as the first line of entry in the Notepad window. This imports the necessary Scanner class to be used in the application.
-
-
3
Declare a new Scanner variable. Add a try-finally block and call the "close()" method of the Scanner class in the finally section. This ensures that any used resources are properly released when the variable is no longer used. For example:
Scanner s = null;
try {
} finally {
if (s != null) {
s.close();
}
}
-
4
Initialize a new Scanner object inside the try block. For example, the following code defines a new Scanner object that read the input from a text file named xanadu.txt:
s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
-
5
Read the input as tokens using the "next()" method of the Scanner object. Use the "hasNext()" method to determine whether there is more input to be read. For example, the following Java code reads one word at a time using the Scanner object and displays it to the screen using the "println()" command:
while (s.hasNext()) {
System.out.println(s.next());
}
-
6
Ensure that the values displayed on the screen are exactly the same as the input read from the file using the Scanner object.
-
1
Tips & Warnings
When reading input from a file, you need to import the necessary Java IO classes as well using the "import java.io.*;" statement.
References
- Photo Credit Hemera Technologies/AbleStock.com/Getty Images