Re: Input from Console
On 2/28/2013 6:47 AM, subhabangalore@gmail.com wrote:
Scanner in = new Scanner(System.in);
name = in.nextLine();
age=in.nextInt();
I'm having a very hard time using Scanner this way. I think it's
perhaps because I normally wrap System.in in a BufferedReader. But
let's in general introduce a third method of reading console input,
which is to use a BufferedReader.
BufferedReader input = new BufferedReader(
new InputStreamReader( System.in ) );
Now you can read lines from the console, which is a little more
intuitive and also works as many users expect. Then the trick is to
extract an integer (or whatever input you are looking for) from the line
of text, which can be done with Scanner.
Full code:
package quicktest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class InputTest {
public static void main( String[] args ) throws IOException {
BufferedReader input = new BufferedReader(
new InputStreamReader( System.in ) );
int age = -1;
do {
System.out.println( "Please enter your age");
String line = input.readLine();
Scanner scan = new Scanner( line );
if( scan.hasNextInt() ) {
age = scan.nextInt();
break;
}
} while( true );
System.out.println( "Age: "+age );
}
}
Study this carefully, and try entering some bad input when it asks for
age. I think you'll see how it works. This could be made more pithy, I
think, but I'll leave it like this because I think it's easier to trace
for someone who's just starting out.