编辑:我将之前的代码更改为将字符串与 !=, 进行比较的代码为 .equals(),但它仍然相同。
我正在尝试制作一个初学者计算器。我被困在这个我无法弄清楚的无限循环中。
首先我尝试了这个:
public void GetValues()
{
System.out.println("Welcome to the \"Math Calculator\"\n");
System.out.print("Type in the first number: ");
int FirstNumber = Scan.nextInt();
System.out.print("Type in the second number: ");
int SecondNumber = Scan.nextInt();
System.out.println("\nWhat operation would you like to do?\n");
System.out.println("For addition, type \"+\"");
System.out.println("For subtraction, type \"-\"");
System.out.println("For multiplication, type \"*\"");
System.out.println("For division, type \"/\"\n");
MathOperation = Scan.next();
while (MathOperation != "+" || MathOperation != "-" || MathOperation != "*" || MathOperation != "/")
{
System.out.print("The value you typed, is not valid. Type again: ");
MathOperation = Scan.next();
}
}
尽管如此,无论我输入什么,我仍然会收到此消息The value you type, is not valid。再次输入:
我就是想不通。我错过了什么?
EDIT2:我将循环更改为:
while (!IsEqual)
{
System.out.print("The value you typed, is not valid. Type again: ");
MathOperator = Scan.next();
if (MathOperator.equals("+") || MathOperator.equals("-") || MathOperator.equals("*") || MathOperator.equals("/"))
{
IsEqual = true;
}
}
现在它可以工作了。感谢所有努力帮助我的人。干杯:)