Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+17 votes

What is "console.nextLine();" in the default package used for?
Why when I delete that code, the program cannot work?

asked in CSC211_Winter2018 by (1 point)

2 Answers

+12 votes
 
Best answer

I believe you are asking about the console.nextLine() that I had in the code after the line int numberNames = console.nextInt();

If so, WARNING, lots of detail to follow.

Here is specifically why that console.nextLine() is there. When the program executes, you are prompted for the number of names. You enter an integer and press Enter. The "input stream" stores the integer and a character representing the Enter key. The nextInt() method consumes the integer from the input stream, but not the Enter char leaving the Enter char in the input stream.

As the loop executes for the user to enter a reversed name, you have a statement something like String name = console.nextLine(); If the Enter char is still in the input stream and it is considered a line so the Enter char is stored into name. Of course that causes problems when your code looks for a comma in the name in the processName method.

The statement console.nextLine(); is "flushing the input stream" (consuming the Enter char from the input stream). Since we didn't need that Enter char, I didn't store it into a variable. By consuming the Enter char, now when you prompt the user to enter a name, the input stream is empty and the code "waits" for you to enter a new line (the line with the reversed name) before the console.nextLine() consumes that line from the input stream storing now the reversed name you entered into the variable name.

answered by (1 point)
selected by
+10 votes

console.nextLine is the line of code that enables the user to enter data into the program. If you do not have this line of code in your program but you want the user to enter something it cannot work.

answered by (1 point)
...