Search code snippets, questions, articles...

pedir números hasta que metan un 0. Mostrar suma de todos.

import java.util.Scanner;
import java.util.ArrayList;

public class App {

    public static int suma(ArrayList<Integer> nums) {
        int suma = 0;
        for (int i = 0; i < nums.size(); i++) {
            suma = suma + nums.get(i);
        } // for i
        return suma;
    } // suma del arraylist

    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);
        int num = 1;
        ArrayList<Integer> nums = new ArrayList<Integer>();

        while (num != 0) {

            System.out.print("Introduce el número: ");
            num = read.nextInt(); // read num
            nums.add(num);

        } // while no es cero

        System.out.println("La suma de todos los números es: " + suma(nums));

    } // main

}
Was this helpful?
0 Comments