简体   繁体   English

Java:仅输出字符串的第一个单词?

[英]Java: only first word of string being output?

I've used the Scanner var = input.nextLine(); 我用过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 消耗您键入的int ,仅此而已,如果没有使用此char(返回行),则一定要返回行

And so input.nextLine(); 所以input.nextLine(); of adress will do it directly 地址将直接执行


2 options : 2种选择:

  1. int age = Integer.parseInt(input.nextLine()); take all line and convert to int 取所有行并转换为int
  2. int age = input.nextInt(); input.nextLine(); take int and use, then consume return like 接受int并使用,然后消耗诸如

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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