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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With