集册 Java实例教程 将数组和单个数组元素传递给方法。

将数组和单个数组元素传递给方法。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

558
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
将数组和单个数组元素传递给方法。



public class Main /*from N  o w  J a v a . c o m*/

{

   public static void main(String[] args)

   {

      int[] array = {1, 2, 3, 4, 5};

      

      System.out.printf(

         "Effects of passing reference to entire array:%n" +

         "The values of the original array are:%n");


      // output original array elements 

      for (int value : array)

         System.out.printf("   %d", value);

   

      modifyArray(array); // pass array reference

      System.out.printf("%n%nThe values of the modified array are:%n");


      // output modified array elements /** 来自 时 代 J a v a**/

      for (int value : array)

         System.out.printf("   %d", value);

   

      System.out.printf(

         "%n%nEffects of passing array element value:%n" +

         "array[3] before modifyElement: %d%n", array[3]);

   

      modifyElement(array[3]); // attempt to modify array[3]

      System.out.printf(

         "array[3] after modifyElement: %d%n", array[3]);

   } 

   

   // multiply each element of an array by 2 

   public static void modifyArray(int array2[])

   {

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

         array2[counter] *= 2;

   } 

   

   
展开阅读全文