Monday, 26 June 2017

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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...