How to call method with array parameter in java?

0

I'm starting in java, I just had one class. So I'm doing a program to add the items to an array, and have to use method. This is my code.

Main:

package exercicio3e4;

public class Principal {

    public static void main(String[] args) {

        Somar x; 
        x= new Somar();
        x.y={1,4,6,8,1};
        x.calcular();


    }

}

Add:

package exercicio3e4;

public class Somar {

    int[] y;
    void calcular() {
        int i = y.length;
        int total=0;
        while (i >= 0) {
            i--;
            total = total + y[i];
        }
        System.out.println("Soma da array: " + total);
    }


}
    
asked by anonymous 24.02.2018 / 13:13

1 answer

2

When pulling the method in your main class you have to pass the necessary parameters to the working method, these parameters also have to be informed in the method.

Example:

public class Principal {
    public static void main(String[] args) {
        Somar x; 
        x= new Somar();
        int [] y={1,4,6,8,1};
        //passando os dados de y para o método
        x.calcular(y);
    }
}

Class Add to the method receiving the parameters

public class Somar {
    //método com parâmetros
    void calcular(int [] a) {
        int total=0;
        //b recebe os valores de []a recebidos no método
        for(int b : a) {
            total = total + b;
        }
        System.out.println("Soma da array: " + total);
    }
}
    
24.02.2018 / 14:18