Search code examples
javawhile-loopswitch-statementblank-line

Ending While loop with blank line(Enter key) inside SwitchCase


*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

Solution

  • 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:

    public class InputTest
    {
    
       public static void main( String[] args )
       {
          Scanner scan = new Scanner( System.in );
          int input = 0;
          do {
             System.out.print( "Choose a function (-1 to exit): " );
             input = scan.nextInt();
             switch( input ) {
                case 1:
                   System.out.println("..1");
                   break;
                case 2:
                   System.out.println("..2");
                   //same while loop here
                   String line = scan.nextLine();
                   System.out.println(">>"+line+"<<");
                   while( line.length() > 0 ) {
                      System.out.println( "  Read line: " + line );
                      line = scan.nextLine();
                      System.out.println(">>"+line+"<<");
                   }
                   break;
             }
          } while( input != -1 );
       }
    }
    

    And its output:

    run:
    Choose a function (-1 to exit): 1
    ..1
    Choose a function (-1 to exit): 2
    ..2
    >><<
    Choose a function (-1 to exit): -1
    BUILD SUCCESSFUL (total time: 11 seconds)
    

    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.