Adding arrays (vectors) with methods

1

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.

Here is the code you have 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 have two problems:

1 - I can not write the result of the sum of a third vector (either by using the somaValores method itself or by trying to pass to the method CreateNewVetor - I tried to solve with only 2 methods first because I thought it would be easier, but anyway I must do with all three). This error occurs int can not be converted to int [] . I do not understand since the left side is a new vector and the right the sum of 2 vectors, for me the two would be int [].

2 - The line return vectorC [5] pops the array, I do not know why it is the same size as the other two.

    
asked by anonymous 08.11.2017 / 11:36

1 answer

0

The first problem lies in this line:

int [] resultado = somaValores(vetorA, vetorB);

The method somaValores() returns int and not int[] .

Change the return type to int[] and instead of return vetorC[5]; do return vetorC;

The second problem is why arrays are zero based . This means that their first position is 0 and not 1 , that is, a 5-position array does not range from 1 to 5, but from 0 to 4.
When doing return vetorC[5]; the sixth position will be searched and since it does not exist, the ArrayIndexOutOfBoundsException exception is thrown.

The correct would be return vetorC[4]; , but as this snippet will be removed, the problem will be removed too.

Tip: In the somaValores() method do not "force" how far your for should go. Use the size of the array as a parameter. See:

Instead of doing so:

for (int i = 0; i < 5; i++)

Do this:

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

As already done in method inserirValores() .

    
08.11.2017 / 11:51