Pages

Sunday 9 September 2012

Topic - Reading input from keyboard

In C we have scanf() function to read the data from the keyboard.
In C++ we have cin>> operator for the same.

what about the same in java ?

answer is  Scanner class with single parameter to Scanner() constructor ie System.in.

the code goes like this

Scanner sc = new Scanner(System.in);
 System.out.println("enter name");
String name = sc.next();
System.out.println("enter age");
int age = sc.nextInt();
System.out.println("name is "+name+" age is "+age);


amazing output is
enter name
kb
enter age
24
name is kb age is 24.

in the above code we passed System.in to Scanner() constructor which points to input stream.
so using scanner object we can read data from keyboard.
next() method always reads String.
nextInt() reads integer value
for byte value use nextByte() and so on for the respective type of data.

Scanner() constructor takes an argument which decides from where the data has to read, whether from file or from input stream or from some variable.

Based on above understanding predict the output of the following piece of code

String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
s.close();

No comments:

Post a Comment