gpt4 book ai didi

java - 使用 Scanner 类的问题

转载 作者:行者123 更新时间:2023-12-01 09:04:44 25 4
gpt4 key购买 nike

该代码可以输入妻子的姓名和年龄,但无法打印儿子的姓名,尽管它正确显示了他们的年龄。

import java.util.Scanner;

public class Check2
{
public static void main(String[] args)
{
String wife;
String son1;
String son2;
int wifeAge;
int son1Age;
int son2Age;

Scanner keyboard = new Scanner(System.in);

System.out.println("Wife's name? ");
wife = keyboard.nextLine();
System.out.println("Her age? ");
wifeAge = keyboard.nextInt();
System.out.println();

System.out.println("First son's name? ");
son1 = keyboard.nextLine();
keyboard.nextLine();
System.out.println("His age? ");
son1Age = keyboard.nextInt();
System.out.println();

System.out.println("Second son's name? ");
son2 = keyboard.nextLine();
keyboard.nextLine();
System.out.println("His age? ");
son2Age = keyboard.nextInt();
System.out.println();

keyboard.nextLine();

System.out.println("My wife's name is " + wife + ". She is " +
wifeAge + " years old.\nOur first son is " +
son1 + ". He is " + son1Age + ".\nOur " +
"second son is " + son2 + ". He is " +
son2Age + ".");
}
}

最佳答案

您的代码中的错误位置有额外的 keyboard.nextLine();

son1 = keyboard.nextLine();
keyboard.nextLine(); // you don't need this here.

son2 = keyboard.nextLine();
keyboard.nextLine(); // nor here

在每个 keyboard.nextInt(); 之后保留额外的 keyboard.nextLine(); 行,您的程序应该可以正常运行。

wifeAge = keyboard.nextInt();
keyboard.nextLine(); // put it here
...
son1Age = keyboard.nextInt();
keyboard.nextLine(); // and here

nextInt() 仅读取整数值,而不读取新行。如果您需要读取新行,则每次从键盘读取整数值时都需要输入 keyboard.nextLine();

希望这有帮助!

关于java - 使用 Scanner 类的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41374736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com