2013-10-18 100 views
0

編輯:我改變了我以前的代碼,在那裏我將比較字符串與!=,以.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; 
     } 
    } 

而現在它的工作原理。感謝所有努力幫助我的人。乾杯:)

+10

比較字符串與'equal()'不與'=='所以修改條件像'!MathOperation.equal(「+」)' –

+0

[why-doesnt -work-on-string](http://stackoverflow.com/questions/17443201/why-doesnt-work-on-string/17443215#17443215) –

+0

@sᴜʀᴇsʜᴀᴛᴛᴀit還是一樣的。 – etritb

回答

1

改變這種

if (MathOperation == "+" || MathOperation == "-" || MathOperation == "*" || MathOperation == "/") 

 if (MathOperation.equals("+") || MathOperation..equals("-") || MathOperation.equals("*") || MathOperation.equals("/")) 
+0

最佳做法,代碼爲「+」。等於(MathOperation),因爲MathOperation可能爲null。 – Hariharan

1

你應該得到你與第二次嘗試得到什麼,即使你寫正確使用equals()比較。

在本質上你有什麼是

if (it's not all four math operations at the same time) 
{ 
    "invalid" 
} 

if條款始終是真實的。

0

您使用無效方法進行比較。

該字符串不是原始類型它是Object。這意味着要與其他人進行比較,您必須從其中針對驗證的元素調用方法equlas

"+".equals(mathOperation)

的另一種方法來解決這個問題是從對象移動到原始炭結構。

char mathOperation = Scan.nextChar(); //Note that variables should start with small letter.

那麼你可以使用==!=運營商獲取結果。

if (mathOperation != '+')

0

當然,你應該總是爲每個對象比較(不只是字符串)表演==操作對象上檢查他們是否在相同的內存空間,比檢查是否兩個不同的指向UE的.equals方法值是相同的。

如果你也很討厭條件邏輯,因爲我做的,你可以去這樣的事情:

Vector<String> allowedMathOperators = new Vector<String>(); 
allowedMathOperators.add("+"); 
allowedMathOperators.add("-"); 
allowedMathOperators.add("*"); 
allowedMathOperators.add("/"); 

String mathOperation = ""; 
Scanner scan = new Scanner(System.in); 

do{ 
    System.out.println("What operation would you like to do?"); 
    mathOperation = scan.next(); 
}while(!allowedMathOperators.contains(mathOperation)); 

我的解決方案的好處是,如果你決定增加對其他運營商的支持,那麼你不必擴展您的條件邏輯,您只需將字符添加到allowedMathOperators :)