Вопрос

I saw the below code in a book. I know that the void method cannot return a value. when I ran the code, the compiler could not print the modified array, while in the book, the values are shown. How can I fix the code to print the modified array?

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; 
    }
}
Это было полезно?

Решение

If I am not mistaken, you should be getting an ArrayIndexOutOfBoundsException for your modifyArray() method. change the for loop in the method to

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

Другие советы

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

This code runs for 6 times thus trying to access the 6th element of your array which doesn't exist. It must be ArrayIndexOutOfBoundsException error. Change above line to:

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

This will work!

The code actually works but there is an error in the method for loop that cause a IndexOutOfBound Exception this is the correct version.

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

The method returns void but you can read the modify values inside the array because you are passing as method argument the reference of the array not a copy of the array. this is a very basic concept of the Java Language you should start reading Passing Information to a Method or a Constructor.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top