【发布时间】: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