4

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

4
  • Can you post your code fragment? Commented Apr 22, 2012 at 9:04
  • 1
    Use something like split and control the count … Commented Apr 22, 2012 at 9:10
  • 2
    If there is no more input in.readLine() will return null. Commented Apr 22, 2012 at 9:14
  • my goal is...i want to find out how many lines of inputs does the user input Commented Apr 22, 2012 at 9:17

2 Answers 2

2

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 ...

Sign up to request clarification or add additional context in comments.

2 Comments

ok i mean he enters the first input and save and compile. when i tried to do String nextLine = in.readLine(); i get error.
@LeafC - I don't understand your comment.
0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.