2013-11-14 130 views
0

我有一個數組:元素多維數組的,爪哇

public String[][] bombBoard = new String[9][9]; 

該數組填充有值(*),但隨機地存在一些其它值(@)。

在節目後來我想告訴用戶如何在(@)時,如果有在附近:

public void loadNumbers() 
{ 
    try 
    { 
     if (bombBoard[bombRow][bombCol] == "@") 
     { 
      System.out.println("You have landed on a bomb!"); 
      //break 
     } 
     else if (bombBoard[bombRow+1][bombCol].equals("@")) 
     { 
      System.out.println("There is a bomb in the vicinity!" + bombBoard[bombRow+1][bombCol]); 
     } 
     else if (bombBoard[bombRow-1][bombCol] == "@") 
     { 
      System.out.println("There is a bomb in the vicinity!" + bombBoard[bombRow-1][bombCol]); 
     } 
     else if (bombBoard[bombRow][bombCol+1] == "@") 
     { 
      System.out.println("There is a bomb in the vicinity!" + bombBoard[bombRow][bombCol+1]); 
     } 
     MORE CODE... 
    } 

} 

它打印:"There is a bomb in the [email protected]"

我想它打印"There is a bomb at 3, 2"

可能很簡單,但我畫的是空白。而不是拉回元素內部的元素,我想要元素索引(我假設)。請halp!

+4

比較'String'值與'String'的'equals'方法,而不是用''==操作符。你在第二種情況下做得正確。 – rgettman

回答

1

我假設你只想打印出@的座標?如果是這樣,你可以這樣做:

System.out.println("There is a bomb at " + bombRow + ", " + bombCol + 1); 

對其他條件使用相同的模式。此外,你想比較字符串使用.equals而不是==(後者只比較引用)。

+0

這個工作稍作修改(而不是bombCol + 1,我用(bombCol + 1)),因爲它沒有做數學沒有parens!謝謝。 –

+0

我改變他們都==,它似乎工作。除了顯而易見的情況,.equals與==的區別是什麼? –

+0

@RichardS我認爲這是因爲字符串實習。 '.equals'會比較實際字符串的內容,而'=='只檢查它們是否指向相同的東西。 –

0

嘗試

System.out.println("There is a bomb in the vicinity!" + (bombRow+1).toString() +"," +bombCol.toString());