Problem does not take me a local variable when I call a class

-2

I have a problem, create a class that has a counter and a boolean array, if the position is even and true , add 1; and if it is odd and false also sum.

I declared an array and initialized it as 0, that is, {} , then in the main I created the array that I use in it, but when I call the class ( nombre_de_la_clase(arreglo) ) it takes 0 that is initialized the arrangement of the class where the meter was.

This is the code:

public class principal {
     public static void main (String [] args) {
    boolean[] array = {true, false, true, false, true, false, true};
    System.out.println (prod(array));
     } 
        public static int prod(boolean [] args) {
        boolean[] arreglo = {};
        int sum=0;
        for (int i=0; i<arreglo.length; ++i) {
                   if (i%2<=0) {
            if (arreglo[i]== true) {
                sum++;
               }
             }
            else {
            if (arreglo[i]== false) {
                sum++;
            }
          }
        }
       return sum;
   }
}
    
asked by Martín Zino 21.03.2018 в 18:14
source

2 answers

1

If I understand your problem well is that when you pass the argument to the prod method you are not capturing the content of the main class's arrego, I frame it with an arrow. I hope it helps you.

public class App {
    public static void main(final String[] args) {
    final boolean[] array = { true, false, true, false, true, false, true   };
        System.out.println(prod(array));
    }

public static int prod(final boolean[] args) {
    /*-->*/boolean[] arreglo = args;
    int sum = 0;
    for (int i = 0; i < arreglo.length; ++i) {
        if ((i % 2) == 0) {
            if (arreglo[i] == true) {
                sum++;
            }
        } else {
            if (arreglo[i] == false) {
                sum++;
            }
        }
    }
    return sum;
}

}

    
answered by 22.03.2018 в 10:47
0

change this:

boolean[] arreglo = {};

for

boolean[] arreglo = args;

Greetings!

    
answered by 23.03.2018 в 18:42