Reputation: 151
I have 3 doubles - a, b and c, passed to a method numPos
as 3 different arguments. I want to count the number of positive valuse among them, hence the method's return type is int
.
I thought about declaring an Array/List
and adding the values to it, checking if the value is greater than 0, but I couldn't even do the first part of my idea - declaring a List
and passing all the values to it. Here's the code I wrote:
public static int numPos(double a, double b, double c) {
return List<double> myList = new List<double>(DoubleStream.of(a,b,c).forEach(i -> myList.add(i))).stream().count();
}
Upvotes: 2
Views: 65
Reputation: 59968
You can easily use:
return Stream.of(a, b, c).filter(x -> x > 0).count();
Note that count()
return long and not int, you need to change the returned type to long.
Important: You really complicate your code, and you have many mistakes that you should to avoid in future.
Upvotes: 4