2014-04-01 58 views
0

改性陣列我看到下面的代碼在一本書。我知道,虛空方法不能返回值。當我跑的代碼時,編譯器無法打印修改後的數組,而在書中,示出的值。我怎樣才能修復代碼打印修改後的數組?打印從空隙方法

public static void main(String[] args) { 

    int[] array = {1, 2, 3, 4, 5}; 
    System.out.println("The values of original array are:"); 
    for(int value: array) 
    { 
     System.out.print(value + "\t"); 
    } 
    modifyArray(array); 
    System.out.println("The values after modified array are:"); 
    for (int value:array) 
    { 
     System.out.print(value + "\t"); 
    } 

}  
public static void modifyArray(int[] b) 
{ 
    for (int counter=0; counter<=b.length; counter++) 
    { 
     b[counter] *=2; 
    } 
} 

回答

6

如果我沒有記錯的話,你應該爲你的modifyArray()方法獲得的ArrayIndexOutOfBoundsException。改變for循環的方法中,以

for (int counter=0; counter<b.length; counter++) // use < not <= 
    { 
     b[counter] *=2; 
    } 
1
for (int counter=0; counter<=b.length; counter++) 

此代碼運行6次從而試圖訪問不存在您的陣列的第六元件。它必須是ArrayIndexOutOfBoundsException異常錯誤。 將以上行更改爲:

for(int counter = 0; counter<b.length; counter++) 

這將工作!

1

該代碼實際上可行,但是在導致IndexOutOfBound異常的循環方法中存在錯誤,這是正確的版本。

public static void modifyArray(int[] b) 
{ 
    for (int counter=0; counter<b.length; counter++) 
    { 
     b[counter] *=2; 
    } 
} 

該方法返回無效,但因爲要傳遞作爲方法參數陣列的參考不是數組的副本可以讀取該陣列內的修改值。這是Java語言的一個很基本的概念,你應該開始閱讀 Passing Information to a Method or a Constructor