2012-01-31 25 views
0

可能重複:
Java string comparison?Java:if/else語句不執行,布爾邏輯變量可能存在問題?

我是相當新的Java和有關於爲什麼我的if/else語句無法執行的問題。該方法的目標是根據從文本文件讀入的符號加載2d數組。符號被轉換爲數字以填充數組。從我所知道的情況來看,用於確定if或if/else語句是否應該執行的布爾邏輯是合理的,但它們都沒有。謝謝您的幫助。

代碼:

public void loadText(Scanner sc) { 

    for (int row = 1; row <= grid.length; row++) { 

     for (int col = 1; col <= grid[row].length; col++) { 

      String x = sc.next(); 

      if ((x == " ") && (row <= 10)) { 
       grid[row][col] = 0; 
      } else if ((x == "*") && (row <= 10)) { 
       grid[row][col] = 1;   
      } else if ((x == "$") && (row <= 10)) { 
       Arrays.fill(grid[row], 0); 
      } else if (row >= 11) { 
       break; 
      } 
     } 
+0

什麼是'x'的價值? – recursive 2012-01-31 14:50:26

+0

嘗試使用.equals而不是== – L7ColWinters 2012-01-31 14:50:47

+0

數組的索引從0開始 – Alexandre 2012-01-31 14:50:59

回答

7

比較使用.equals.equalsIgnoreCase字符串。

6

比較字符串時,是使用

" ".equals(x) in stead of x == " " 
5

爲了您的字符串比較的代碼,你需要用.equals更換==一個很好的做法()如

if (" ".equals(x) && (row <=10)) { 

} 

==檢查兩個對象是同一個對象,equals()方法檢查它們是否代表相同的事物。在Java中equals()可以被類重寫,以做正確的事情,但==不能。

3

雙等號將任何非原語的地址進行比較。

由於String是一個類的實例,你應該使用equals方法這樣

for (int row = 1; row <= grid.length; row++) { 

    for (int col = 1; col <= grid[row].length; col++) { 

     String x = sc.next(); 

     if ((x.equals(" ")) && (row <= 10)) { 
      grid[row][col] = 0; 
     } else if ((x.equals("*")) && (row <= 10)) { 
      grid[row][col] = 1;   
     } else if ((x.equals("$")) && (row <= 10)) { 
      Arrays.fill(grid[row], 0); 
     } else if (row >= 11) { 
      break; 
    } 
} 
+0

或者可能是「」.equals(x)在空值的安全一側。 – Johnydep 2012-01-31 15:43:39

+0

這個答案(和其他人喜歡它)解決了這個問題。我真的很感謝大家的幫助。當我變得更有經驗時,我希望我可以回報你們所有人。謝謝。 – 2012-01-31 19:21:51

-1

可以使用char數據類型,而不是Stringx讓你的工作做,如果符號是單個字符

(x == '$') && (row <= 10)

+0

我說用字符而不是字符串 – MozenRath 2012-01-31 16:13:29

-1

我認爲所有的這些答案,都是跳到結論,是的,我同意大多數人的,但你的問題是,你不知道x是什麼。

您需要登錄它,但嘗試添加一行

System.out.println(x); 

You will see what is being compared. 

A test shows what you have could work; 


import org.junit.Test; 
import static org.junit.Assert.assertTrue; 

public class BooleanLogicTest { 

@Test 
public void testLogical() { 
    String x = " "; 
    boolean result = x == " "; 
    assertTrue("Could be true", result); 
} 

@Test 
public void testCompare() { 
    String x = " "; 
    boolean result = " ".equals(x); 
    assertTrue("Could be true", result); 
} 

@Test 
public void testLogicalX() { 
    String x = "*"; 
    boolean result = x == "*"; 
    assertTrue("Could be true", result); 
} 

@Test 
public void testCompareX() { 
    String x = "*"; 
    boolean result = "*".equals(x); 
    assertTrue("Could be true", result); 
    System.out.println(x); 
} 

}

+1

不要分心新的孩子。你可以給他一個關於jUnits的單獨課程 – MozenRath 2012-01-31 15:04:50

+0

爲什麼它被拒絕了嗎?哦,你認爲檢查/測試只有在你編程數年後纔有效。可憐的唯一方法就是知道它失敗的原因是找出價值是什麼並對其進行測試。否則,你在猜測。我想你假設凱旋王不想知道測試,但我沒有。 – 2012-01-31 15:05:46

+0

這不是我的意思。你可以在知道原始答案後用這種方式回答大部分家庭作業問題 – MozenRath 2012-01-31 15:09:00