I have a problem when adding elements of a vector (it doesn't add them and prints each element instead of printing the total sum of the elements) and I don't know what is wrong, I hope you can help me!
What I want is for it to add up all the items I have entered and print them.
Example:
Enter the number of items: 3 Enter value: 2 Enter value: 2 Enter value: 2 The sum is: 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();
}
}
You have a typo in
main
, you have putman
in its placeIt would be corrected like this:
Other than this the code is correct and works according to your requirement. It seems that the problem cannot be reproduced