Monday, June 10, 2013

Scanner Class in Java

The Scanner class was introduced in JDK1.5. So, make sure you have at least this version installed before actually using it. It is available in java.util package. It can be used to obtain input from console, a file, a String, etc.
The Scanner class splits input into substrings (also known as tokens), which are separated by delimiters. The default delimiter (if not specified) is any white space.
Below is the program written in Java that demonstrates how to input from console (keyboard) using Scanner class:
import java.util.*;
class ScannerDemo{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter an integer:");
int i=sc.nextInt();
System.out.println("You entered "+i);
System.out.print("Enter a real number:");
double d=sc.nextDouble();
System.out.println("You entered "+d);
System.out.print("Enter an boolean value:");
boolean b=sc.nextBoolean();
System.out.println("You entered "+b);
System.out.print("Enter a word:");
String w=sc.next();
System.out.println("You entered "+w);
sc.useDelimiter("\n");
System.out.print("Enter an sentence:");
String s=sc.next();
System.out.println("You entered "+s);
}
}

The useDelimiter() method is used to set the delimiter you want. By default, the Scanner class stops accepting data as soon as it encounters a blank space while accepting input through the keyboard. To change this behavior, we use useDelimiter() method.

No comments:

Post a Comment