简体   繁体   中英

Java: only first word of string being output?

I've used the Scanner var = input.nextLine(); It works for my name variable but not address? Here is my code:

Scanner input = new Scanner(System.in);

System.out.println("What is your name?");
String name = input.nextLine();

System.out.println("How old are you?");
int age = input.nextInt();

System.out.println("Where do you live?");
String address = input.nextLine();

System.out.println("Your name is " + name + ".\n You are " + age + " years old." + "\n You live at " + address + ".");

And here's what it's displaying:

What is your name?
Yassine assim
How old are you?
17
Where do you live?
Your name is Yassine assim.
 You are 17 years old.
 You live at .

int age = input.nextInt(); consumes the int you typed but that's it, you surely return to line after if BUT this char (return line) has not been consumed

And so input.nextLine(); of adress will do it directly


2 options :

  1. int age = Integer.parseInt(input.nextLine()); take all line and convert to int
  2. int age = input.nextInt(); input.nextLine(); take int and use, then consume return like

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM