Tuesday 25 October 2016

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...