Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Adding multiple user inputs into arraylist

Tags:

java

arraylist

I am attempting to read an infinite amount of numbers input on the same line from user (separated by a space) and print the square of all values above 0 - all without using for loops.

For example...

Input:

1 2 3 4 -10 -15

Output:

30

Below is the code I have so far:

ArrayList<Integer> numbers = new ArrayList<Integer>();

    //insert into array if > 0
    int x = sc.nextInt();
    if(x > 0){
        numbers.add(x);
    }

    //square numbers array
    for (int i = 0; i < numbers.size(); ++i) {
        numbers.set(i, numbers.get(i) * numbers.get(i));
    }

    //sum array
    int sum = 0;
    for(int i = 0; i < numbers.size(); ++i){
        sum += numbers.get(i);
    }
    System.out.println(sum);

As you can see I am just scanning one input from the user as i'm not sure how to tackle storing infinite input. Furthermore, I am using for loops for my two equations.

Thanks

like image 774
0xgareth Avatar asked Mar 27 '26 07:03

0xgareth


1 Answers

Since you're adding the square of each number, you don't really need any list, just a single number to which you add the square for each number you read from the input. Something like:

int result = 0;    
Scanner scanner = new Scanner(System.in);

while(scanner.hasNextInt()){
    int num = scanner.nextInt();
    if(num > 0)
        result += num * num;
}

System.out.println(result);
like image 111
Kraylog Avatar answered Mar 29 '26 20:03

Kraylog