How to call method with the java array parameter?

Asked

Viewed 816 times

0

I’m starting in java, I only had one class. So I’m making a program to add up the items in an array, and I have to use method. This is my code.

Leading:

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);
    }


}
  • 1

    Just use void calcular(int[] x) { ... } and to call new Somar().calcular( array )

1 answer

2


By pulling the method in its main class you have to pass the necessary parameters for the method to work, these parameters also have to be reported 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 with method receiving 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);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.