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


*amended input scan
i'm trying end while loop 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 integrate within main program(while loop placed within int switch case within do-while loop) program skips codes @case2 , continue do-while loop

int input; do{       system.out.print("choose function (-1 exit): ");       input=scan.nextint();       switch (input)       {           case 1:           break;           case 2:           //same while loop here           break;       }    }while(input!=-1); 

sample output:

choose function (-1 exit): 1 choose function (-1 exit): 2 //skip case2 coding choose function (-1 exit): 1 choose function (-1 exit): -1 //program ends 

i'm not 100% sure, think scanner not reading input. there's blank line (a newline character) in buffer when scanner starts read, returns empty line, causes line length 0 , exit loop immediately.

here's best guess current program is:

public class inputtest {     public static void main( string[] args )    {       scanner scan = new scanner( system.in );       int input = 0;       {          system.out.print( "choose function (-1 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 output:

run: choose function (-1 exit): 1 ..1 choose function (-1 exit): 2 ..2 >><< choose function (-1 exit): -1 build successful (total time: 11 seconds) 

you can see line prints >><< means read empty. think left on newline '2' above, since newline isn't part of number 2 , left in buffer.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -