2012-01-22 45 views
0

我在填充二維數組時遇到了一些困難。之前,我根據用戶輸入構建了一個尺寸爲二維的陣列。基本上我需要檢查這個語句是否有效(仍然在數組維度中)。有誰知道我該怎麼做?二維數組方法構造

(square[0 - i][dimension/2 + i]) // is valid/still in array dimensions 

感謝

+0

你能更準確? –

+0

寫一個if語句? –

+0

這是一個有效的Java語句語法,但是我們無法告訴您它是否是邏輯上正確的,而不是基於您提供的有限信息。你需要問一個更好的問題。 –

回答

1

如果你的意思是你要檢查輸入的用戶是否尺寸不太小了,你做你的事,你要使用square.length和方[0 ] .length(對於子數組)。 例子:

int array[5][6] = new int; 

System.out.println(array.length); 
System.out.println(array[0].length); 

這將返回:

5 
6 

所以你可以使用。長度來檢查值是否是你所需要的範圍內。

0

您可以做的另一件事是將「可疑」語句放在try-catch塊中,catch塊捕獲ArrayIndexOutOfBoundsException並採取相應的措施(例如在屏幕上打印錯誤)。

像這樣:

Scanner in = new Scanner(System.in); 

int i, j; 

i = in.nextInt(); 
j = in.nextInt(); 

in.close(); 

try 
{ 
    System.out.println (the_array[i][j]); //anything else can go here (maybe add that array element to another array ?) 
} 
catch (ArrayIndexOutOfBoundsException e) 
{ 
    System.err.println ("invalid input"); //anything else can go here (maybe ask for another input ?) 
}