Bri*_*ian 1 java while-loop switch-statement do-while
我正在为一个类的项目工作,并且可以使用一些帮助来弄清楚为什么我的代码的行为方式.赋值是提示用户输入两个整数并选择要对它们执行的算术运算,同时避免"除以零"场景.这是我的代码的一部分:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我执行代码时,我得到以下内容:
"请输入第一个操作数的值.
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:
Run Code Online (Sandbox Code Playgroud)
但它的行为方式仍然完全相同.此外,如果我输入一个无效的数字,程序只会挂起,并且根本不会返回任何内容.
但它的行为方式仍然完全相同.此外,如果我输入一个无效的数字,程序只会挂起,并且根本不会返回任何内容.
因为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));
Run Code Online (Sandbox Code Playgroud)
它在执行循环体之后检查一次条件.因此它总是输入代码的这一部分,这意味着将要求用户输入至少两次.您需要使用while循环,它将在输入之前检查循环的条件.
例如
while ((reallyWantZero < 1) || (reallyWantZero > 2)) {
System.out.println(newLine + "You must type either 1 or 2 and press enter.");
reallyWantZero = input.nextInt();
}
Run Code Online (Sandbox Code Playgroud)