我正在为一个类的项目工作,并且可以使用一些帮助来弄清楚为什么我的代码的行为方式。赋值是提示用户输入两个整数并选择要对它们执行的算术运算,同时避免“除以零”场景。这是我的代码的一部分:
import java.util.Scanner;
public class Program3
{
public static void main(String[] args)
{
double operandOne;
double operandTwo;
char newLine = '\n';
Scanner input = new Scanner (System.in);
//"input" is an object which calls for input from the keyboard.
System.out.print("This program will request values for two operands ");
System.out.println("and perform an arithmetic operation of your choice on them.");
System.out.println(newLine + "Please enter a value for the first operand.");
operandOne = input.nextDouble();
System.out.println("Thank you. Please enter a value for the second operand.");
operandTwo = input.nextDouble();
// This section explains what's going on to the user and requests input for the operands.
if ( operandTwo == 0 )
{
System.out.print("You will not be able to perform division if the ");
System.out.println("second operand is zero!");
System.out.println(newLine + "Please choose an option:");
System.out.println("Type 1 to select a new value for the second operand.");
System.out.println("Type 2 to continue with a value of zero.");
// You can't divide by zero! Are you SURE you want to use that number?
int reallyWantZero = input.nextInt();
do
{
System.out.println(newLine + "You must type either 1 or 2 and press enter.");
reallyWantZero = input.nextInt();
}
while ((reallyWantZero < 1) || (reallyWantZero > 2));
{
switch (reallyWantZero)
{
case 1:
System.out.println(newLine + "Please enter a new value for the second operand.");
operandTwo = input.nextDouble();
break;
case 2:
System.out.println(newLine + "Okay, we will proceed.");
break;
}
}
}
当我执行代码时,我得到以下内容:
“请输入第一个操作数的值。
1
谢谢。请输入第二个操作数的值。
0
如果第二个操作数为零,您将无法执行除法!
请选择一个选项:
键入1以为第二个操作数选择新值。 键入2继续值为零。
2
您必须输入1或2并按Enter键。
2
好的,我们会继续。“
我不明白为什么第一次不接受输入2继续,但是第二次接受。任何人都可以帮助解释发生了什么以及如何纠正它吗?
提前致谢!
编辑:
我将代码修改为:
好的,我理解你的意思,但它似乎不起作用。我将我的代码修改为:
while ((reallyWantZero < 1) || (reallyWantZero > 2));
{
System.out.println(newLine + "You must type either 1 or 2 and press enter.");
reallyWantZero = input.nextInt();
}
switch (reallyWantZero)
{
case 1:
但它仍然表现完全相同。此外,如果我输入的数字无效,程序就会挂起,并且根本不会返回任何内容。
但它仍然表现完全相同。此外,如果我输入的数字无效,程序就会挂起,并且根本不会返回任何内容。
答案 0 :(得分:5)
因为do...while
循环总是至少执行一次
do
{
System.out.println(newLine + "You must type either 1 or 2 and press enter.");
reallyWantZero = input.nextInt();
}
while ((reallyWantZero < 1) || (reallyWantZero > 2));
在执行循环体之后检查一次条件。因此它总是输入代码的这一部分,这意味着将要求用户输入至少两次。您需要使用while循环,它将在输入之前检查循环的条件。
E.g。
while ((reallyWantZero < 1) || (reallyWantZero > 2)) {
System.out.println(newLine + "You must type either 1 or 2 and press enter.");
reallyWantZero = input.nextInt();
}
答案 1 :(得分:1)
为什么不
while (reallyWantZero != 1 && reallyWantZero != 2) {
System.out.println("enter 1 or 2");
reallyWantZero = input.nextInt();
}
//do stuff here with that info