tags:

views:

85

answers:

3

Does any one know why my nextLine() not working after a for loop? It's always skip the nextLine() and go direct to the if statement. See below for more details

int[] a = new int[3]

for(int i=0; i<3;i++) { a[i] = nextInt(); }

String b = nextLine();

if(b == "go") { ....... } else { ..... }

A: 

What do you mean by not working? You mean to say nextLine() method is not getting called. As per the code you pasted it will 100% call the nextLine() method.

Bhushan
A: 

The statement involving nextLine should always be executed there (unless an exception is thrown). You don't show the implementation for nextLine. Are you sure it isn't executed. A few System.err.println("blah") scattered might help.

Btw: the String comparison should almost certainly be b.equals("go"). If b might be null either check explicitly for that or write the expression "go".equals(b).

Tom Hawtin - tackline
+2  A: 

I am guessing that maybe what you are doing is asking for the user to input the integers and then press enter. When it parses the integers, it just parses and removes the integers. But of course the newline that they pressed is still in the stream. And then when you ask for nextLine(), it returns immediately because there is already a line in the stream (the one that ends in the newline that was pressed for the integers). And maybe you had actually expected the nextLine() to wait for an additional line after the integers had been entered, but that is not what is happening. Is this right?

newacct