Monday, January 14, 2019

user input string and integers in Java





    System.out.print("Name : ");
String name = in.nextLine();

System.out.print("Age : ");
int age = in.nextInt();


System.out.print("City : ");
String city = in.nextLine();


the output will be :



Name : test



Age : 20




BUILD SUCCESSFUL



when i debug them, it won't read the user input for "city" . but when i changed the data type for "age" to string, it will read. how can i kept the data type of age to int with the system reading the user inputs for city ?


Answer



As there is still a new line character in the buffer after reading the age, change it to..



System.out.print("Name : ");
String name = in.nextLine();

System.out.print("Age : ");

int age = in.nextInt();
//add
in.nextLine();

System.out.print("City : ");
String city = in.nextLine();

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...