Reputation: 53
ok so I am working this project where you have to do something with inputs from user
let says if he enters
"12 3"
But he doesn't input the second input
And let's say if i call it with
String something = in.readLine();
if i were to call
String nextLine = in.readLine();
i get errors. how do i check if there's no second input?
public static void main(String [] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //ctr + shift + o
String eachLine = in.readLine(); //ex. "12 5"" or "AB 12"
String nextLine = in.readLine();
if the user input
"3 2" <<
but does not enter the second one..i get nullpointerexception
Upvotes: 4
Views: 3265
Reputation: 8101
You can use Timer class for this purpose.
Have a look here
Something like..
TimerTask task = new TimerTask(){
public void run(){
if( input is empty ){
System.out.println( "you input nothing. exit..." );
System.exit( 0 );
}
}
};
Schedule the Timer
..
Timer timer = new Timer();
timer.schedule( task, timeoutTime);
//Read the input
String nextLine = in.readLine();
//Cancel the timer..
timer.cancel();
Upvotes: 0
Reputation: 719239
It depends on what you mean by "he doesn't input the second input":
If you mean that the user enters the EOF character (e.g. CTRL-D on Linux), then what happens is that the readLine()
method will return a null
, which your application can (and should) explicitly test for.
If you mean that the user simply enters nothing, then nothing happens. Your application will just sit there waiting for the user to enter the next line. To deal with that, you need some kind of timeout mechanism ...
Upvotes: 2