java - While loop doesn't work with two inputs -


i'm working in larger program have while loop asks 2 questions , gets 2 inputs. whenever second loop of while loop happens, displays both outputs without taking input after first 1 , takes input second one.

here small example demonstrate problem:

public class tests{      public static void main(string args[]){          scanner scan = new scanner(system.in);          while (true){              system.out.println("please enter name: ");             string name = scan.nextline();             system.out.println("please enter age: ");             int age = scan.nextint();              system.out.println(name + age);         }        } } 

the first loop through works fine. second time through though, outputs

please enter name:  please enter age: 

it skips on first input in every loop after first one. why?

you need call

scan.nextline(); 

after line

int age = scan.nextint(); 

this consumes end of line character in buffer.

an alternate approach use scan.nextline() , parse input integer this:

int age = integer.parseint(scan.nextline()); 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -