Saturday 4 May 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...