-1
I am trying to perform an exercise in Java that creates an A vector and adds even and odd values in 2 vectors, B and C, respectively. However, I am required to declare the size of these vectors before using them, so that there are empty positions in memory. For example:
int[] A = new int[10];
for (int i = 0; i < A.length; i++){
System.out.printf("Digite um valor para A[%d]: ", i);
A[i] = scan.nextInt();
}
int[] B = new int[A.length];
int[] C = new int[A.length];
for (int i = 0; i < A.length; i++){
if (A[i] % 2 == 0){
B[i] = A[i];
} else{
C[i] = A[i];
}
}
System.out.println();
System.out.println("Você digitou os seguintes valores pares: ");
for (int i = 0; i < B.length; i++){
if (B[i] != 0){
System.out.printf("%d ", B[i]);
}
}
System.out.println();
System.out.println("Você digitou os seguintes valores ímpares: ");
for (int i = 0; i < C.length; i++){
if (C[i] != 0){
System.out.printf("%d ", C[i]);
}
}
I wonder if there is any way to create a vector without an initial size limit, which adds the elements as needed, without leaving empty positions in memory.
Your first solution is exactly what I was looking for. Thank you very much!
– Matheus Cavalcante
But I was testing here my for using Arraylist and saw that it only accepts the loop in this format : for (int n : pairs) { System.out.printf("%d ", n); }
– Matheus Cavalcante
It doesn’t work using the for the way I was asking the question?
– Matheus Cavalcante
@Matheuscavalcante Com
ArrayList
would have to be:for (int i = 0; i < pares.size(); i++) { System.out.printf("%d ", pares.get(i)); }
- but if you just want to iterate for the values, I thinkfor (int n: pares)
more succinct and direct– hkotsubo
I get it, thank you!
– Matheus Cavalcante