1

I am making a binary search tree (BST) and a randomized BST. All of my methods for both of these work and I'm stuck on what I feel is more simple. The code that is failing is pretty simple. As an aside, I'm using standard redirection to read the values, so I input a lot of values at once, not one at a time.

while ( console.hasNextInt() ) {
   key = console.nextInt();
   System.out.println(key);
   head.remove( key );
}

Where console is the name of my scanner, and key is a global variable used to read in the keys for the trees. Debugging shows that it goes through the loop correctly until after the final integer is read. After that it appears to reenter the while loop even though there are no more integers to read. I'm obviously making a mistake somewhere but it's not obvious to me and I've spent a couple of hours trying to reword this to no avail. Any help would be greatly appreciated.

EDIT - An example of what I am inputting is:

820426496 648711744 834882112 261937632 475255968 311993216 834882112

It reads in every number until 834882112 and then enters back into the while loop and I don't know why.

As far as the code, this is exactly the code that is messing up. Everything else is just setting up the scanner, etc.

2
  • Not enough code to say what the problem is. Commented Oct 21, 2012 at 12:43
  • What do you enter in the console? The loop will only end if there's something to read and if it's not an integer. Commented Oct 21, 2012 at 12:45

1 Answer 1

2

As I said in my comment, hasNextInt() returns true if the next token in the stream is an int, and false if it is not an int. Once the loop has read the last int, hasNextInt() simply waits for the next token to be entered to decide if it's a valid integer or not. If you want to stop the loop, you need to enter something which is not an integer.

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

3 Comments

Follow up question for JB Nizet: My understanding was that if there is no more input to consume that it wouldn't have a nextInt so it would return false would exit the while loop.
The scanner doesn't know if there is no more input to consume until the input stream is closed. And System.in is only closed when the program ends.
Thanks, JB. Unfortunately I'm unable to add anything to that string, but that at least will point me in the right direction.

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.