I have a problem when adding elements of a vector (do not add them and print each element instead of printing the total sum of the elements) and I do not know what is wrong, I hope you can help me!
What I want is for you to add all the elements you have entered and print them.
Example:
Ingrese la cantidad de elementos: 3 Ingrese valor: 2 Ingrese valor: 2 Ingrese valor: 2 La suma es: 6
package _Vector_Tamaño;
import java.util.Scanner;
/*
Desarrollar un programa que permita ingresar un vector de n elementos, ingresar n por teclado.
Luego imprimir la suma de todos sus elementos
*/
public class Problema1 {
private Scanner teclado;
private int[] elementos;
private int suma;
public void cargar() {
teclado = new Scanner(System.in);
int n;
System.out.print("Ingrese la cantidad de elementos: ");
n = teclado.nextInt();
elementos = new int[n];
for(int f = 0; f < elementos.length; f++) {
System.out.print("Ingrese valor: ");
elementos[f] = teclado.nextInt();
}
}
public void suma() {
suma = 0;
for(int f = 0; f < elementos.length; f++) {
suma = suma + elementos[f];
}
}
public void imprimir() {
System.out.println("La suma es: " + suma);
}
public static void man(String[] ar) {
Problema1 prob = new Problema1();
prob.cargar();
prob.suma();
prob.imprimir();
}
}