編輯:我改變了我以前的代碼,在那裏我將比較字符串與!=,以.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();
}
}
不過,不管是什麼我輸入,我仍然得到這個消息您鍵入的值,是無效的。再次輸入:
我只是無法弄清楚。我錯過了什麼?
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;
}
}
而現在它的工作原理。感謝所有努力幫助我的人。乾杯:)
比較字符串與'equal()'不與'=='所以修改條件像'!MathOperation.equal(「+」)' –
[why-doesnt -work-on-string](http://stackoverflow.com/questions/17443201/why-doesnt-work-on-string/17443215#17443215) –
@sᴜʀᴇsʜᴀᴛᴛᴀit還是一樣的。 – etritb