2
I have an exercise to do: create a method where the user enters the values of 2 vectors, then create a method to sum the values of the 2 vectors and finally a third method that shows the new vector created.
Follow the code created so far:
import java.util.Arrays;
import javax.swing.JOptionPane;
public class Vetor2 {
public static void main(String[] args) {
int[] vetorA = new int[5];
int[] vetorB = new int[5];
inserirValores(vetorA, vetorB);
somaValores(vetorA, vetorB);
int [] resultado = somaValores(vetorA, vetorB);
criaNovoVetor(novoVetor);
}
public static void inserirValores(int[] a, int[] b) {
for (int i = 0; i < a.length; i++) {
a[i] = Integer.parseInt(JOptionPane.showInputDialog(null, "Insira o " + (i + 1) + "o valor do vetor A: "));
b[i] = Integer.parseInt(JOptionPane.showInputDialog(null, "Insira o " + (i + 1) + "o valor do vetor B: "));
}
}
public static int somaValores(int[] a, int[] b) {
int[] vetorC = new int[5];
for (int i = 0; i < 5; i++) {
vetorC[i] = a[i] + b[i];
}
return vetorC[5];
}
public static void criaNovoVetor(int [] novoVetor) {
JOptionPane.showMessageDialog(null, "O novo vetor é: " + Arrays.toString(novoVetor));
}
}
I’m in two trouble:
1 - I cannot record the result of the sum of a third vector (either using the somaValue method itself, or trying to pass to the method creatinNovoVetor - I tried to solve only with 2 methods first because I thought it would be easier, but anyway need to do with all three). That error occurs int cannot be converted to int[]. I don’t understand since on the left side is a new vector and on the right the sum of 2 vectors, for me the two would be int[].
2 - The line Return vetorC[5] overflows the array, I don’t know why since it is the same size as the other two.
Which way out of
somaVetores
? An integer with all the sum of the 10 elements or a vector whose 5 elements are the sums of the respective box ofa
andb
?– Jefferson Quesado