Doubt about method of sum

Asked

Viewed 479 times

-2

How to make a method that takes as parameter an integer vector, computes the sum and returns the sum?

I tried to do so, but it did not work, the sum is not held.

public static void main(String[] args) {
  int[] vetor = new int[10];
  int numeros;
  Scanner e = new Scanner(System.in);
  for (int i = 0; i <= 10; i++) {
    System.out.println("digite os valores dos vetores");
    vetor[i] = e.nextInt();
    numeros = vetor[i];

    int soma = 0;
    int resultado = somarVetores(numeros,soma);

    System.out.println(resultado);
  }
}

static int somarVetores(int numeros, int soma) {
  soma = soma + numeros;
  return soma;
}

2 answers

1

public static void main(String[] args) {
  int[] vetor = new int[10];
  int numeros;
  Scanner e = new Scanner(System.in);
  for (int i = 0; i <= 10; i++) {
    System.out.println("digite os valores dos vetores");
    vetor[i] = e.nextInt();
    numeros = vetor[i];

    int soma = 0; //sempre é zero
    int resultado = somarVetores(numeros,soma);

    System.out.println(resultado);
  }
}

public static int somarVetores(int numeros, int soma) {
  soma = soma + numeros;
  return soma;
}

The original code problem (above) beyond the unused variables is the sum is always made with zero and the number typed by the user soon does not do the expected.

Solution

You can solve this at once or when the user informs the number already performs the addition in a totalizing variation and after/outside of for display the result.

If you really need to divide this task, do it in two steps. The first is to store the entered values the second is to receive this array and do the somatoria.

public class t {
    public static void main(String[] args) {
        int[] vetor = new int[10];
        Scanner e = new Scanner(System.in);
        for (int i = 0; i < 3; i++) {
            System.out.println("digite os valores dos vetores");
            vetor[i] = e.nextInt();
        }
        System.out.println("Resultado "+ somarVetores(vetor));
    }

    public static int somarVetores(int[] numeros) {
        int soma = 0;
        for (int i = 0; i < 3; i++) soma += numeros[i];
       return soma;
    }
}

1

Follow an example:

public static void main(String[] args) {
    int[] vetor = new int[10];
    int numeros;
    Scanner e = new Scanner(System.in);
    int soma = 0;
    for (int i = 0; i <= 10; i++) {
        System.out.println("digite os valores dos vetores");
        vetor[i] = e.nextInt();
        numeros = vetor[i];
    }

    soma = somarVetor(vetor);
    System.out.println(soma);
}

static int somarVetor(int[] numeros) {
    int soma = 0;
    for (int numero : numeros) {
        soma += numero;
    }
    return soma;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.