Java Scanner class
The Java Scanner class is a class in java.util package , which allows the user to read values of various types. It is a simple text scanner which can parse primitive types and strings using regular expressions . It has a rich set of API which generally used to break down the input to Scanner constructor into tokens . Also, it can parse the tokens into primitive data types using java regular expressions. The following Java program reads two numbers from the console and display the sum of the numbers.
import java.util.*;
import java.io.*;
public class TestClass{
public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number...");
int num1 = sc.nextInt();
System.out.println("Enter second number...");
int num2 = sc.nextInt();
System.out.println("Sum is : " + (num1+num2));
}
catch (Exception e){
e.printStackTrace();
}
}
}
The following Java program read the contents of a text file by using Scanner.
import java.util.*;
import java.io.*;
public class TestClass{
public static void main(String[] args) {
try {
File file = new File("d:\\test.txt");
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String line = scan.nextLine();
System.out.println(line);
}
scan.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
Related Topics