Java Scanner class reads formatted input and returns it to you.
We can use Scanner class to read input from the console, a file, a string, or any source that implements the Readable interface or ReadableByteChannel.
A Scanner can be created for a String, an InputStream, a File, or any object that implements the Readable or ReadableByteChannel interfaces.
The following sequence creates a Scanner that reads the file Test.txt:
FileReader fin = new FileReader("Test.txt"); Scanner src = new Scanner(fin);
FileReader implements the Readable interface.
Thus, the call to the constructor resolves to Scanner(Readable)
.
The following line creates a Scanner that reads from standard input, which is the keyboard by default:
Scanner conin = new Scanner(System.in);
System.in
is an object of type InputStream. The call to the constructor maps to Scanner(InputStream)
.
The next sequence creates a Scanner that reads from a string.
String instr = "10 1.8 string from demo2s.com."; Scanner conin = new Scanner(instr);
To use Scanner, follow this procedure:
hasNextXXX()
methods. nextXXX()
methods. close()
. The following sequence shows how to read a list of integers from the keyboard.
Scanner conin = new Scanner(System.in); int i; // Read a list of integers. while(conin.hasNextInt()) { i = conin.nextInt(); // ... }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scannerObject = new Scanner(System.in); System.out.println("Enter two whole numbers"); System.out.println("separated by one or more spaces:"); int n1, n2; n1 = scannerObject.nextInt();// w w w .j a va 2 s . c o m n2 = scannerObject.nextInt(); System.out.println("You entered " + n1 + " and " + n2); System.out.println("Next enter two numbers."); System.out.println("A decimal point is OK."); double d1, d2; d1 = scannerObject.nextDouble(); d2 = scannerObject.nextDouble(); System.out.println("You entered " + d1 + " and " + d2); System.out.println("Next enter two words:"); String s1, s2; s1 = scannerObject.next(); s2 = scannerObject.next(); System.out.println("You entered \"" + s1 + "\" and \"" + s2 + "\""); s1 = scannerObject.nextLine(); //To get rid of '\n' System.out.println("Next enter a line of text:"); s1 = scannerObject.nextLine(); System.out.println("You entered: \"" + s1 + "\""); } }