我使用过Scanner var = input.nextLine(); 它适用于我的名字变量,但不适用于地址? 这是我的代码:
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 + ".");
以下是它的显示内容:
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 .
答案 0 :(得分:2)
int age = input.nextInt();
会消耗您键入的int
,但是,如果此消息(返回行)尚未消耗,您肯定会返回到行
所以地址的input.nextLine();
会直接执行
2个选项:
int age = Integer.parseInt(input.nextLine());
占据所有行并转换为int
int age = input.nextInt(); input.nextLine();
接受int并使用,然后使用return返回