*amended input scan
I'm trying to end a while loop with enter key/blank line
Test codes below works fine.
Scanner scan = new Scanner(System.in);
String line;
while ( (line=scan.nextLine()).length() > 0)
{
System.out.println(line);
}
However, when I integrate it within my main program(while loop placed within int switch case within a do-while loop) the program skips the codes @case2 and will continue do-while loop
int input;
do{
System.out.print("Choose a function (-1 to exit): ");
input=scan.nextInt();
switch (input)
{
case 1:
break;
case 2:
//same while loop here
break;
}
}while(input!=-1);
Sample output:
Choose a function (-1 to exit): 1
Choose a function (-1 to exit): 2
//skip case2 coding
Choose a function (-1 to exit): 1
Choose a function (-1 to exit): -1
//program ends
I'm not 100% sure, but I think that scanner is not reading all input. There's a blank line (a newline character) in the buffer when the Scanner starts to read, so it returns an empty line, which causes your line length to be 0 and exit the loop immediately.
Here's my best guess as to what your current program is:
And its output:
You can see that the line prints as
>><<
which means it was read but empty. I think the left over newline from '2' above, since a newline isn't part of the number 2 and would be left in the buffer.