How do I pass the array to the main method after calculating the sum of values?

Abby :

So this is the code I currently have. I am trying to calculate the sum of all the numbers in the second method and then return it to the main method to display but I am getting confused with how to do this properly. Any help is welcome!

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;

  }
}
jack chiou :

If want to calculate sum via method, you can just return an integer.

    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;

    }

By the way the for loop you write is going to do nothing because it just run length times with no command according to ; is the first command each time the executing loop see . You should write like this

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

or

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

to run mutiple code.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=396765&siteId=1