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