简体   繁体   English

从 void 方法打印修改后的数组

[英]printing a modified array from a void method

I saw the below code in a book.我在一本书中看到了下面的代码。 I know that the void method cannot return a value.我知道 void 方法不能返回值。 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.如果我没记错的话,你应该为你的modifyArray()方法得到一个ArrayIndexOutOfBoundsException change the for loop in the method to将方法中的 for 循环更改为

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.这段代码运行了 6 次,因此试图访问不存在的数组的第 6 个元素。 It must be ArrayIndexOutOfBoundsException error.它必须是 ArrayIndexOutOfBoundsException 错误。 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.该代码实际上有效,但 for 循环方法中存在错误,导致 IndexOutOfBound 异常,这是正确的版本。

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.该方法返回 void 但您可以读取数组内的修改值,因为您将数组的引用作为方法参数传递而不是数组的副本。 this is a very basic concept of the Java Language you should start reading Passing Information to a Method or a Constructor .这是 Java 语言的一个非常基本的概念,您应该开始阅读将信息传递给方法或构造函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM