Console input in java using scanner

Often we have to read input from the user through console and most of the time we need to read primitive types(int,long,float,char ...). For reading an array of integers as input , we often coded as shown below. That is we input was read as a string and converted to integer for using it.

int[] array = new int[size];
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int j = 0; j < array.length ; j++) {
int k = Integer.parseInt(br.readLine());
array[j] = k;
}
}catch (Exception e) {
e.printStackTrace();
}

From J2SE 5.0 onwards Java has added a new classes called Scanner which is basically used for reading primitive types of data. The above code can be implemented with the Scanner class as shown below.

int[] array = new int[size];
try {
Scanner in = new Scanner(System.in);
for (int j = 0; j < array.length ; j++) {
int k = in.nextInt();
array[j] = k;
}
}catch (Exception e) {
e.printStackTrace();
}

Scanner class is pretty much simpler to work with than the BufferedReader, when you have to read only the primitive types.

Scanner class can also be used for parsing input based on regular expression. For more details check http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html

0 comments: