Doubt about filling Array in Java

1

I'm having trouble solving the following exercise:

  
  • Create a class with a main method;
  •   
  • Create a 10-position int array and popule using for
  •   
  • Print all the values in the array and, for even values, display the value followed by the word "even" (use the% operator to   par)
  •   

Firstly I did this, but it is giving compilation error:

public class MeuArray {
    public static void main (String[] args) {
        int[] MeuArray = new int[10];
        for (int i = 0; i < 10; i++){
            if (MeuArray[i] % 2 == 0) {
         System.out.prinln("O vetor é par:", MeuArray[i]);
        } else {
            System.out.println("O vetor é impar:" MeuArray[i]);
        }

 }
 }
}

I changed to this code and the outputs are showing the result 0:

public class MeuArray {
    public static void main (String[] args) {
        int[] MeuArray = new int[10];
        for (int i = 0; i < 10; i++){
            if (MeuArray[i] % 2 == 0) {
         System.out.println(MeuArray[i]);
        } else {
            System.out.println(MeuArray[i]);
        }

 }
 }

}
    
asked by anonymous 09.08.2018 / 16:03

2 answers

2

Your second code is not wrong, but as I mentioned in the comments, you barely created the array, and without popula- tion, it is already sweeping your values.

The result is always zero because an array of primitive type int , when created, is already filled with 0 as the initial value in all positions.

To populate an array, the logic is the same one you are already using to scan it, create a loop that goes from position 0 to tamanhodoarray-1 and assigns values to each position, it would look something like this:

/ p>

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

    meuArray[i] = <valor que voce ira atribuir>;

}

Remembering that if you use a literal value to assign the position of the array, all positions will be the same, the exercise does not talk to user input, but if it is allowed to use, you can use the Random class to generate random numbers

Another point remembered by the user @hkotsubo is how you are concatenating values within println() , to concatenate strings in java, if you use the symbol + and not , or space, even if you spelled the print method correctly, it would give compilation error for this reason.

The correct form would look something like below:

System.out.println("isto é uma string literal" + variavelQualquer)
    
09.08.2018 / 16:15
-1

What do you want to put in the array? first the Array you created has 10 positions, you can fill it like this:

MyArray [i] = i;

In this way you will fill the position i, which in this case is 0 to 9; with the number itself.

Place this command under the for command, on top of the first if and see what happens.

    
09.08.2018 / 16:44