Archive for October, 2007
Make use of java.util.Scanner
Suppose if you want to accept an input from a Keybord ,in a basic application like public static void main() kind of programe you will need to import java.io.BufferdReader and io.InputStreamReader … you make long sentence like:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
This is something very hard snip….
one of the weird thing is , if you want to convert to integer type then you must parse it:
int num = Integer.parseInt(br.readLine());
and to convert , double , then,
double d = Double.parseDouble(br.readLine());
and code goes on….
this is two way process on every code , to accept and to convert; this really kills the time and performance…
One of the best way to manage, is to use the class called “Scanner” which is shiped in j2se5.0… found in java.util package.
This AIP is a simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods !!!
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in) String str = sc.next(); //read string int num = sc.nextInt(); // read integer long lnum = sc.nextLong(); // read long double d = sc.nextDouble(); // read double and more..... read javaDoc 5.0 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(br.readLine()); the above code just boils down to : Scanner sc = new Scanner(System.in) int num = sc.nextInt(); Scanner is very useful when you are using regular expression , searching patterns... String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close(); prints the output 1 2 red blue
3 comments October 8, 2007
