Scanner in Java with Example. How to read input from Key Board & File using java.util.Scanner Class?

Scanner in Java :
The Scanner class in java.util (java.util.Scanner) can read input from Keyboard (System.in) or Files and parse primitive types and strings using regular expressions. Scanner breaks its input text into tokens using a delimiter . By default, a scanner uses white space to separate tokens. The resulting tokens can be converted into values of different types using the various next methods.
I have exaplained with various examples , how to read input from System.in , File

Example 1 : The following code allows a user to read a number from System.in and calculates Surface Area and Perimeter of a Rectangle




import java.util.*;

public class Areaoftriangle
{
public static void main(String []args){
Scanner scanner = new Scanner(System.in);

System.out.print("Enter base (in cm): ");
double b = scanner.nextDouble();

System.out.print("Enter height (in cm): ");
double h = scanner.nextDouble();

double area=b*h*1/2;
System.out.println("Area of Triangle =" +area);
}
}


Running the Above Prgram

Output :

D:\as2\j2eeforum>java AreaRectangle
Enter Breadth 50
Enter Height 20
Area of Rectangle = 1000.0
Perimeter of Rectangle = 140.0

Example 2 : The fllowing code allows to read lines from a file "AreaRectangle.java" and prints the contents of Java file line by line..





import java.util.*;
import java.io.*;

public class FileRead
{
public static void main(String []args){
try {
Scanner fr = new Scanner(new File("d:\\as2\\AreaRectangle.java"));
fr.useDelimiter (System.getProperty("line.separator"));

while (fr.hasNext()) {
System.out.println(fr.next());
}
fr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

}
}


Running the above program will print all lines of the "AreaRectangle.java" one by one.

0 comments:

Post a Comment

 
Copyright 2011 Java Online