我正在学习Java类,并且我使用hasNext命令停留在一个赋值上,以便检查两个用户输入的变量以确保它们是数字的。这是我到目前为止所做的。
扫描仪sc =新扫描仪(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();
}
} }
出现错误时我收到的输出是:
请输入数值,然后重试。输入第一面:请输入数值,然后重试。进入第一面:
我打算只收到:
请输入数值,然后重试。进入第一面:
答案 0 :(得分:1)
那是因为你的第二个语句的None
使你的程序回到while循环的第一行(下一次迭代)。
要克服它,您应该将第二个侧扫描语句放在它自己的continue;
循环中。像这样:
while