2011-07-18 68 views
0

我正在編寫一個課程程序,用於分析輸入的不同產品代碼。這很簡單,但我有一個問題。如果用戶輸入「E」或「e」,我試圖結束一個循環。但是,它並沒有結束循環。這是在while語句的結尾,因此將loop設置爲false應該結束它,它甚至不會輸出總數,所以我已經搞砸了。代碼是一個字符串類型。字符串問題 - Java

 // Prompt the user for another company code or exit 
     System.out.print("Enter the company code or type 'e' to exit: "); 

     // Input the user's company code 
     code = scan.nextLine(); 

     // Check to see if the user wants to exit 
     if (code == "e" || code == "E") { 
      // Output final statistics 
      System.out.print("Total valid codes: " + valid + "/n"); 
      System.out.print("Total banned codes: " + banned); 

      // End the loop  
      loop = false; 
     } 

任何想法?謝謝!

+0

我看不到任何代碼迴路? –

+0

你可以放入循環碼嗎?我想你想用「打破」而是結束循環,但我不知道你的循環是什麼樣的。 – MacGyver

回答

6

您需要使用code.equals("e") || code.equals("E")(或者只是code.equalsIgnoreCase("e"))。這是因爲==確實身份比較(「是Xÿ相同的對象?」),而equals確實比較(「做Xÿ具有相同的價值?」) 。

+0

非常感謝你和所有回答的人。 –

+0

作爲一個後續問題,我採用TRV2475A5R-14並創建一個只有2475的字符數組。我需要確保它只包含數字字符。你如何推薦我這樣做? –

+0

@Brooks:你應該在網站上提出一個新的問題。但是,這裏有一個單行的答案:'code.matches(「\\ d +」)'。 –

1

使用.equals()沒有==

1

比較字符串通過equals==

if (code.equals("e") || code.equals("E")) { 
1

使用.equals進行比較時,字符串比較字符串。

你的情況,你甚至可以用

if (code.equalsIgnoreCase("e")) { 

的原因是==檢查是否兩個對象是同一個對象。你可以有兩個不同的字符串對象表示相同的字符串。

1

使用.equalsIgnoreCase("e"),==比較內存中對象的地址和.equals(String)區分大小寫。

1

試試這個:

** LOOP * {

// Prompt the user for another company code or exit 
    System.out.print("Enter the company code or type 'e' to exit: "); 

    // Input the user's company code 
    code = scan.nextLine(); 

    // Check to see if the user wants to exit 
    if (code.equals("e") || code.equals("E")) { // <====== see new code 
     // Output final statistics 
     System.out.print("Total valid codes: " + valid + "/n"); 
     System.out.print("Total banned codes: " + banned); 

     // End the loop  
     //loop = false; 
     break; // <====== see new code 
    } 

}

4

當比較Strings你應該始終使用equals方法而不是==,所以

if ("e".equals(code) || "E".equals(code)) 

可能是你想要的。

原因是Strings是Java中的特殊對象。它們是不可變的,它們可以被實現以優化存儲器使用。常量(例如代碼中的「e」和「E」)由編譯器自動執行,但scanLine方法可能會返回非實際字符串,因此==比較將失敗。

記住,當我們談論的對象,==檢查參考平等值相等,即a == b的意思是「做ab指向同一個對象嗎?」。有可能a.equals(b)爲真,但a == b爲假。

+0

+1爲談論實習;我目前正在撰寫一些幻燈片,而我所談論的主題之一是具有同等價值的不可變對象如何合併和/或實現。 :-D –

2

使用equalsIgnoreCase()

您的代碼將是

if (code.equalsIgnoreCase("e")) { 
      // Output final statistics 
      System.out.print("Total valid codes: " + valid + "/n"); 
      System.out.print("Total banned codes: " + banned); 

      // End the loop  
      loop = false; 
     } 
0

我想說的東西像代碼它能夠更好地使用Java枚舉。使用枚舉可以使用==運算符進行比較。

0

這是更好地使用

code.equalsIgnoreCase("e") 
0

使用https://stackoverflow.com/a/513839/1394464

== tests for reference equality. 

.equals() tests for value equality. 

因此給出的解釋,如果你真的想測試兩個字符串是否有你應該使用.equals相同的值()而不是==。

所以

if(code == "e" || code == "E") 

應該成爲

if(code.equals("e") || code.equals("E"))