如有必要,你可以选择性遍历数组的一部分元素。以下代码将数组的前五个元素翻了一番。注意第12行所涉及到的复杂循环条件使用&&来确保数组不会越界。

public class ArrayWorker
{
   private int[ ] values;

   public ArrayWorker(int[] theValues)
   {
      values = theValues;
   }

   public void doubleFirstFive()
   {
     for (int i = 0; i < values.length && i < 5; i++)
     {
       values[i] = values[i] * 2;
     }
   }

   public void printArray()
   {
      for (int val: values)
      {
         System.out.println(val);
      }
   }

   public static void main(String[] args)
   {
     int[] numArray = {3, 8, -3, 2, 20, 5, 33, 1};
     ArrayWorker worker = new ArrayWorker(numArray);
     worker.doubleFirstFive();
     worker.printArray();
   }
}

你甚至可以从数组中间开始并遍历剩余的元素。这对于有偶数个和奇数个元素的数组是否都能得到预期的效果?修改以下代码并测试奇偶个数的影响。

public class ArrayWorker
{
   private int[ ] values;

   public ArrayWorker(int[] theValues)
   {
      values = theValues;
   }

   public void doubleLastHalf()
   {
     for (int i = values.length / 2; i < values.length; i++)
     {
       values[i] = values[i] * 2;
     }
   }

   public void printArray()
   {
      for (int val: values)
      {
         System.out.println(val);
      }
   }

   public static void main(String[] args)
   {
     int[] numArray = {3,8,-3, 2};
     ArrayWorker worker = new ArrayWorker(numArray);
     worker.doubleLastHalf();
     worker.printArray();
   }
}


0:00

Given the following values of a and the method doubleLast what will the values of a be after you execute: doubleLast()?

private int[ ] a = {-20, -15, 2, 8, 16, 33};

public void doubleLast()
{

   for (int i = a.length / 2; i < a.length; i++)
   {
      a[i] = a[i] * 2;
   }
}
i3开始增加。
3

Given the following values of a and the method mystery what will the values of a be after you execute: mystery()?

private int[ ] a = {-20, -15, 2, 8, 16, 33};

public void mystery()
{

   for (int i = 0; i < a.length/2; i+=2)
   {
      a[i] = a[i] * 2;
   }
}
注意a2为单位增加,满足条件的索引只有02
4


陈 欣

AADPS创始人

发表评论