【问题标题】:printing a modified array from a void method从 void 方法打印修改后的数组
【发布时间】:2014-04-01 08:22:12
【问题描述】:

我在一本书中看到了下面的代码。我知道 void 方法不能返回值。当我运行代码时,编译器无法打印修改后的数组,而在书中显示了值。如何修复代码以打印修改后的数组?

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; 
    }
}

【问题讨论】:

    标签: java arrays void


    【解决方案1】:

    如果我没记错的话,您应该为您的 modifyArray() 方法获得一个 ArrayIndexOutOfBoundsException。将方法中的for循环更改为

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

    【讨论】:

      【解决方案2】:
      for (int counter=0; counter<=b.length; counter++)
      

      此代码运行了 6 次,因此试图访问数组中不存在的第 6 个元素。一定是 ArrayIndexOutOfBoundsException 错误。 将上面的行更改为:

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

      这行得通!

      【讨论】:

        【解决方案3】:

        代码确实有效,但 for 循环方法中存在错误,导致 IndexOutOfBound 异常,这是正确的版本。

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

        该方法返回 void 但您可以读取数组内的修改值,因为您将数组的引用而不是数组的副本作为方法参数传递。这是您应该开始阅读的 Java 语言的一个非常基本的概念 Passing Information to a Method or a Constructor.

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多