【问题标题】:Issues while error checking two variables with hasNext method使用 hasNext 方法检查两个变量时出现问题
【发布时间】:2017-02-27 05:58:58
【问题描述】:

我正在学习 Java 课程,但我被困在使用 hasNext 命令错误检查两个用户输入的变量以确保它们是数字的分配上。这是我目前所拥有的。

扫描仪 sc = new Scanner(System.in);

    String choice = "y";
    double firstside;
    double secondside;

    //obtain user input
    while (choice.equalsIgnoreCase("y")) {


    System.out.println("Enter First Side: ");
    if (sc.hasNextDouble()) {
        firstside = sc.nextDouble();

    } else {
        sc.nextLine();
        System.out.println("Please enter a numeric value and try again.");
        continue;
    }

    while (true){
    System.out.println("Enter Second Side: ");
    if (sc.hasNextDouble()) {
        secondside = sc.nextDouble();
        break;
    } else {
        sc.nextLine();
        System.out.println("Please enter a numeric value and try again.");
    }
    }

    //calculate results
    double hypotenusesquared = Math.pow(firstside, 2) + Math.pow(secondside, 2);
    double hypotenuse = Math.sqrt(hypotenusesquared);

    //display results
    String output = "Hypotenuse = " + hypotenuse;
    System.out.println(output);
    System.out.println("Would you like to continue? Y/N?");
    choice = sc.next();
}

} }

出现错误时我收到的输出是:

请输入一个数值,然后重试。输入第一面:请输入数值并重试。进入第一面:

我打算只收到:

请输入一个数值,然后重试。进入第一面:

【问题讨论】:

  • 这是因为您有一个要求“第一面”和“第二面”的大循环。如果你回到循环的开头,它会再次询问“第一面”,因为那是循环开头的内容。您的程序没有任何东西可以让它回到“第二面”问题。要解决这个问题,请将“第二面”输入代码放在自己的循环中。
  • 为了扩展@ajb 所说的内容,continue 关键字将重复整个循环,而不仅仅是再次询问第二个变量。因此,如果您为第二个值输入非双精度值,它会将您送回起点。您可以将第二个输入问题放入自己的循环中,也可以将其放入 do/while 循环中。

标签: java


【解决方案1】:

那是因为您的第二条语句的continue; 使您的程序返回到 while 循环的第一行(下一次迭代)。

要克服它,您应该将第二个侧扫描语句放在它自己的while 循环中。像这样的:

System.out.println("Enter Second Side: "); //move this inside below loop if you want to prompt user for each invalid input.

while(true) {
    if (sc.hasNextDouble()) {
        secondside = sc.nextDouble();
        break; //if we get double value, then break this loop;
    } else {
        sc.nextLine();
        continue; //you can remove this continue
    }
}

【讨论】:

  • 我添加了您建议的更改,但我仍然遇到问题。我的控制台输出如下所示:
  • 请输入直角三角形的两条边。输入第一面:g 请输入数值并重试。输入第一面:3 输入第二面:g 请输入数值并重试。输入第二面:请输入数值并重试。进入第二面:3 Hypotenuse = 4.242640687119285 你想继续吗?是/否? y 输入第一面: g 请输入数值并重试。输入第一面:请输入数值并重试。进入第一面:
  • @mrgopher 这似乎是一个有效的输出。我可以看到您的程序从Enter Second Side 递归询问,直到提供有效输入。这不是你想要的吗?
  • 我的问题是它会两次说明错误消息,并提示两次输入无效输入的边号。
  • @mrgopher 您能否更新您的问题并提供您期望的示例回复?
猜你喜欢
  • 2016-06-25
  • 1970-01-01
  • 2019-12-15
  • 2011-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-05
  • 1970-01-01
相关资源
最近更新 更多