Doubts about sum method

-3

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

I tried to do this, but it did not work, the sum is not done.

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;
}
    
asked by anonymous 25.08.2017 / 21:00

2 answers

1

Here's 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;
}
    
25.08.2017 / 21:16
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 problem of the original code (above) in addition to the variables not used is the sum is always made with zero and the number entered by the user soon does not do as expected.

Solution

You can solve this at once only when the user reports the number already doing the addition in a totalizing variation and after of for displays the result.

If you really need to split this task, do it in two steps. The first is to store the values typed, the second is to receive this array and make the summation.

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;
    }
}
    
25.08.2017 / 21:14