Tuesday, 5 November 2013

Java scanner


Java Scanner is one of the easiest and fastest way of getting input from user through console. The Scanner class is present in the java.util package. A Scanner object can take input from console or a file. Even if the program has a good GUI to accept user data scanner always prove useful to read data files. A Scanner breaks the input in to token using the delimiter, the default delimiter is white spaces.
A scanner class has 8 different constructors. They are as follows,

  1. Scanner(File source) 
  2. Scanner(File source, String charsetName) 
  3. Scanner(InputStream source)
  4. Scanner(InputStream source, String charsetName) 
  5. Scanner(Readable source) 
  6. Scanner(ReadableByteChannel source) 
  7. Scanner(ReadableByteChannel source, String charsetName) 
  8. Scanner(String source) 

Scanner can be created using any of the above constructor according to need.
Example:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

The Above syntax accepts the input from user through console. Here “nextInt()” method is used to accept the input of integer type. There are methods like “nextDouble()”, “nextFloat()” etc to accept data in their respective format.

Scanner object can also accept data from a file.
Example:
Scanner data1 = new Scanner(new FileStream("filename.txt"));
 while (in.hasNextInt())
{
total +=in.nextInt();
}

The above example accepts all the integer values from the file and add the in the variable “total”. Here the filename is passed to the FileStream constructor to read the file. The “hasNextInt()” method is used to read all the integer values from the file.

The “close()” method is used to close the scanner.
Exmple :
sc.close();

Hence, Java Scanner is one of the convenient way of accepting user data through console or file.

No comments:

Post a Comment