首页 > 解决方案 > 计算值的总和后如何将数组传递给 main 方法?

问题描述

所以这是我目前拥有的代码。我正在尝试计算第二种方法中所有数字的总和,然后将其返回到主要方法进行显示,但我对如何正确执行此操作感到困惑。欢迎任何帮助!

public class Main {

  public static void main(String[] args) {

    int[] population = {
      693417,
      457502,
      109985,
      107360,
      103773,
      13145,
      5469
    };

    int[] total = computeTotal(population);
    for (int i = 0; i < total.length; i++);
    System.out.print(total + " ");

  }

  public static int computeTotal(int[] population) {

    int[] population2 = {
      693417,
      457502,
      109985,
      107360,
      103773,
      13145,
      5469
    };
    return population2;

  }
}

标签: java

解决方案


如果想通过方法计算总和,你可以只返回一个整数。

    public static void main(String[] args) {
        int[] population = { 693417, 457502, 109985, 107360, 103773, 13145, 5469 };

        int total = computeTotal(population);
        System.out.print(total + " ");

    }

    public static int computeTotal(int[] Popu) {

        int sum=0;
        for(int i=0;i<Popu.length;i++)
            sum+=Popu[i];
        return sum;

    }

顺便说一句,您编写的 for 循环将什么也不做,因为它只是运行长度时间而没有命令根据;是每次执行循环看到的第一个命令。你应该这样写

for(int i=0;i<Popu.length;i++)
    only one line code end with ;

或者

for(int i=0;i<Popu.length;i++){
...
}

运行多个代码。


推荐阅读