1
I’m having trouble solving the following exercise:
- Create a class with a main method;
- Create an int array with 10 positions and popule using for;
- Print all array values and, for even values, display the value followed by the word "even" (use % operator to know when it is par)
First I did so, 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 switched 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]);
}
}
}
}
What about when you populate the array? Notice you’re already creating it and displaying it without populating it?
– user28595
The code is not wrong, you just forgot to do what was requested in the second exercise item, which is popule using for
– user28595
Yes, I noticed, I don’t know how to populate an array with for in java, I’m beginner.
– Jéssica Santos
The first code does not compile because you used
prinln
instead ofprintln
, and it would be right to have a+
between the text and the value:"O vetor é impar:" + MeuArray[i]
instead of"O vetor é impar:" MeuArray[i]
and"O vetor é par:" + MeuArray[i]
instead of"O vetor é par:", MeuArray[i]
. About the second code, the array was missing, as already commented. You need to make two loopsfor
, one to popular the values, and the other to print them– hkotsubo