Reputation: 621
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
Upvotes: 3
Views: 5713
Reputation: 1219
Using lambdas :
ArrayList<Integer> numbers = new ArrayList<>();
while (sc.hasNextInt()) {
int x = sc.nextInt();
if (x > 0) {
numbers.add(x);
}
}
int sum = numbers.stream().map(i -> i * i).reduce((xx, yy) -> xx + yy).get();
System.out.println(sum);
Upvotes: 0
Reputation: 1074
As said in the first answer, you don't need an ArrayList.
But if you insisted on doing it that way, here is a solution:
To store the numbers, use this code:
while(sc.hasNextInt()){
int x = sc.nextInt();
if(x > 0){
numbers.add(x);
}
}
And the for loops can be avoided this way:
Instead of:
for (int i = 0; i < numbers.size(); ++i) {
numbers.set(i, numbers.get(i) * numbers.get(i));
}
You can use:
List<Integer> newNumbers = numbers.stream().map(x->x*x).collect(toList());
Upvotes: 1
Reputation: 2751
You can use split
after reading the line and then perform your calculation:
int result = 0;
Scanner scanner = new Scanner(System.in);
String a[] = scanner.nextLine().split(" ");
for (String aa : a) {
if (Integer.parseInt(aa) > 0) {
result = result + Integer.parseInt(aa) * Integer.parseInt(aa);
}
}
System.out.println(result);
I/P: 2 3 1 -44 -22
O/P 14
Upvotes: 0
Reputation: 2340
You can refactor your program using array list in this way:
ArrayList<Integer> numbers = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
while(in.hasNextInt()){
int x = in.nextInt();
if(x > 0){
numbers.add(x * x);
}
}
int sum = 0;
for(int i = 0; i < numbers.size(); i++){
sum += numbers.get(i);
}
System.out.println(sum);
Upvotes: 0
Reputation: 7553
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);
Upvotes: 2