Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

user input string and integers in Java [duplicate]

Tags:

java

string

int

    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 ?

like image 710
Athirah Hazira Avatar asked Jun 13 '26 01:06

Athirah Hazira


1 Answers

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();
like image 125
Scary Wombat Avatar answered Jun 14 '26 13:06

Scary Wombat