2013-10-19 32 views
0

我基本上写了一个布尔数组[x] [y],x,y是坐标,如果它的确存在一个炸弹。getter为一个布尔数组[] []

林具有与该吸气麻烦,

我到目前为止

boolean[][] bombArray = new boolean[Total_Columns][10]; 

for(x=0,x<Total_Colmns,x++){ 
    bombArray[x][0] = true; 
    } 

public boolean getBombArray(int x,int y){ 
    if(bombArray[x][y] .equals(true){ 
    return true; 
    } 
    else{ 
    return false; 
    } 
} 

我的主要看起来像这样

main() 
boolean isBomb = myPanel.getBombArray(x,y) //x and y being the cursor coordinates 
if(isBomb){ 
.... 
.... 
.... 
.... 
{ 
else{ 
.... 
.... 
.... 
} 

基本上电网将是这样

 
********* 
......... 
......... 
......... 
......... 
......... 
......... 
......... 
......... 

可是我得到的是不工作的,它不断抛出异常

+0

有什么例外? – AsemRadhwi

+1

请注意:没有理由使用getBombArray中的条件,只需返回该位置的值:'return bombArray [x] [y];' –

回答

3

这条线:

if(bombArray[x][y] .equals(true){ 

缺少括号之前一个右括号。

你的函数的正确版本是:

public boolean getBombArray(int x,int y){ 
    // bombArray[x][y] has type 'boolean', which isn't an object, it's a primitive 
    // (don't use .equals() on primitives) 
    if(bombArray[x][y] == true){ 
     return true; 
    } else{ 
     return false; 
    } 
} 

但是你可以很显著简化这个东西我觉得是更清楚一点:

public boolean getBombArray(int x,int y){ 
    // bombArray[x][y] is true if there's a bomb, false otherwise 
    return bombArray[x][y]; 
} 
3

你应该得到一个编译时间由于这里缺少括号导致的误差:

if(bombArray[x][y] .equals(true) 
    ... 

整个函数bo dy应该是:

return bombArray[x][y]; 
+0

另外,'boolean'没有'.equals '函数(虽然'布尔'确实) –

+0

另一个编译时错误。谢谢@MarkElliot。 – Tarik

1

异常发生在运行时。我怀疑这个代码能够抛出异常,因为它不能编译。让我们通过它:

for(x=0,x<Total_Colmns,x++){ 
    bombArray[x][0] = true; 
} 

以匹配您的数组声明你想Total_Columns在这里,而不是Total_Colmns。逗号应该是分号,而x变量可能是未声明的。你的循环应该是这样的:

for (int x = 0; x < Total_Columns; x++) { 
    bombArray[x][0] = true; 
} 

另外,如果你没有复制和粘贴代码单独片段到你的问题,好像你的循环是任何方法之外。它不会在那里工作。它可能属于你的类的构造函数。

在吸气您有:

if(bombArray[x][y] .equals(true){ 
    return true; 
} else { 
    return false; 
} 

boolean是原始类型,而不是一个Object,所以它不具有equals方法。您只能使用bombArray[x][y] == true。您还错过了if声明中的关闭)。实际上,因为你的数组元素已经是一个布尔你可以直接返回它:

public boolean getBombArray(int x, int y) { 
    return bombArray[x][y]; 
} 

如果从传递光标位置获得ArrayIndexOutOfBoundsException S,你可能想限制你的吸附剂中的X & y坐标。例如:

if (x < 0 || x >= bombArray.length || y < 0 || y >= bombArray[x].length) return false; 

如果仍然出现错误和异常情况,请显示真实的错误消息。它们包含帮助您解决问题的信息。 “不工作”是不够的信息。

+0

现在感谢它的工作,没有例外,但它的行为总是像isBomb = false,我可以发布我的代码,看看你能否帮我找到某种错误? – user2896762

+0

公共布尔getBombArray(INT的x,int y)对{ \t \t如果(X < 0 || x > TOTAL_COLUMNS - 1 ||ý< 0 || y > TOTAL_ROWS - 2){ \t \t \t返回假; \t \t} \t \t否则{ \t \t \t返回bombArray [X] [Y]; \t \t} \t \t \t} – user2896762

+0

@ user2896762我建议你打印出所有的X和你正在阅读,以确保这些都是正确的年。你是否将“光标位置”除以每个网格的大小? – Boann