Sum up numbers with Arraylist in Java

avatar

A small application which sum up numbers from the Scanner input.

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

public class SumUp {

    public static List<Integer> inputNumbers(){
        List<Integer> numbers = new ArrayList<Integer>();
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        String[] numberlist = input.split(" ");
        sc.close();

        for(var n = 0; n < numberlist.length; n++){
            Integer value;
            try {
                value = Integer.valueOf(numberlist[n]);
                numbers.add(value);
            } catch ( NumberFormatException e){
                // continue
            }
        }
        return numbers;
    }

    private static void sumup(List<Integer> numbers){
        int sum = 0;
        for(var n = 0; n < numbers.size(); n++){
            sum += numbers.get(n);
        }
        System.out.println(sum);
    }

    public static void main(String[] args){
        List<Integer> n = SumUp.inputNumbers();
        SumUp.sumup(n);
    }
}



0
0
0.000
3 comments
avatar

While I'm more interested in programming with Python, I understand that the size of conventional arrays in Java can't be modified, so ArrayLists are the way to go.

That being said, congrats on creating the project, that inspires me to post my own. Good luck!

0
0
0.000