Java,数组作为双倍元素的方法的参数,然后返回数组

时间:2015-11-05 03:13:08

标签: arrays methods foreach

我已经陷入了课堂上的问题而研究并没有帮助。到目前为止,我有原始数组创建10个100到200之间的随机数,一个Arrays类将它从最小到最大排序,第二个方法使用原始数组作为参数,返回结果,并打印在对于主方法下的每个循环。我需要为每个循环添加一个语句,它接受每个返回的值并将它们加在一起,然后在第3个输出行上打印它们。我一直在努力,但是我将每个值的总和添加到了每个值的末尾。

import java.util.Arrays;

public class Project7and81 {
public static void main(String[] args) {
    int[] randnums = new int[10];
    for (int i =0; i < randnums.length; i++){
        randnums[i] = 100 + (int)(Math.random() * (200-100) + 1);}
        java.util.Arrays.sort(randnums);
        System.out.println(Arrays.toString(randnums));  
    for (double e: doubleMyArray(randnums)){
        System.out.print((int) e + " ");

    }
    }
public static int[] doubleMyArray(int[] randnums){
    int[] doubledNums = new int[randnums.length];
    for (int i = 0; i < randnums.length; ++i)
        doubledNums[i] = randnums[i] * 2;
        return doubledNums;
}
}   

1 个答案:

答案 0 :(得分:0)

您正在更新范围有限的值;它只存在于你的循环中。

 public static int[] doubleMyArray(int[] randnums) {
   for (int e: randnums)
   {
        e = (e * 2);
        // Scope of e ends here; e stops existing.
   }
   return randnums;
 }

您应该更新(根据您的偏好)原始数组中的值或新数组。由于你想要更新传入的数组(这是不好的做法,除非明确指向!),否则不要这样做,循环是:

 public static int[] doubleMyArray(int[] randnums) {
   int i = 0;
   for (int value : randnums) // Could do this as for (;;) loop, which would be nicer imo
   {
        randnums[i++] = value * 2;
   }
   return randnums;
 }

要显示加倍的数字并返回总和(但不显示总和),请使用此循环:

 public static int displayArrayAndReturnSum(int[] randnums) {
     int total = 0;
     for (int value : randnums)
     {
         System.out.print(" " + value);
         total += value;
     }
     System.out.println("");
     return total;
 }