Hi! I'm writing a code that'll make a binary search tree in console and I seem to be running into a problem.
The second loop or so, for loop will repeat for some reason. After some debugging, I saw that it was because that x is being registered as a null string and immediately going into the switch - case code without asking for user input, but what I don't know is how?
Here is my code down below:
If you have any ideas as to why this is happening, please let me know. Thanks!
DT is correct; x (what a poor name for a String) isn't null. Don't go saying, “null String,” because there is no such thing, unless it is "null". You have found misleading information about whatScanner#nextLine()does. Have a look at our FAQ, whih I thinkk will help you.
I believe you are running into a classic Scanner gotcha. "nextLine()" reads all characters up to a new-line. IF a new-line is already pending in the queue, then nextLine() will consume that and return the String. If a pending new-line is all that is in the queue then the String that is immediately returned is an empty String. So, where does a pending new-line come from? "nextInt()" for one, consumes all digits until it encounters a non-digit. If you entered in a number followed by Enter then the non-digit is a new-line. So, now a new-line is sitting in the queue waiting to be read and along comes nextLine() which says, ah, ha, I found a new-line so therefore I have a whole line. When, in fact you haven't entered a line at all. So to fix this you have to flush out the new-line after calling nextInt() and before calling the "real" nextLine().
I prefer not to create a Scanner directly, but to have a utility class called KeyboardInputs (or similar) and use that. I recently edited the FAQ I linked to yesterday to include suggestions about utility classes.
And I see I put the wrong link in . I have somehow gone back to my post about the Beatles, where I suggested calling nextLine() twice. This is the FAQ I thought I had quoted.