Reputation: 43
i am beginner and here is the method I am struggling with.
Write a method called percentEven that accepts an array of integers as a parameter and returns the percentage of even numbers in the array as a real number. For example, if the array stores the elements {6, 2, 9, 11, 3}, then your method should return 40.0. If the array contains no even elements or no elements at all, return 0.0.
here is what I have so far...
public static double percentEven(int[]a){
int count = 0;
double percent = 0.0;
if (a.length > 0){
for ( int i = 0; i < a.length; i++){
if ( a[i] % 2 == 0){
count++;
}
}
percent =(count/a.length)*100.0;
}
return percent;
}
i keep returning 0.0 when array contains a mix of even and odd elements but works fine for all even element array or all odd array? i can't see where the problem is? thanks in advance.
Upvotes: 4
Views: 2085
Reputation: 88
List<Integer> numbers = Arrays.asList(a);
int number = numbers.stream().filter(n->n%2==0).count();
int percent = number*100.0/numbers.size();
I have done this in java 8
Upvotes: 0
Reputation: 525
@Bathsheba : Well said, thanks for the suggestion.
Here is sample code :
public class PercentEven {
public static void main(String args[]){
int count = 0;
int[] a={2, 5, 9, 11, 0}; // this can be dynamic.I tried diff values
double percent = 0.0;
if (a.length > 0){
for ( int i = 0; i < a.length; i++){
if ( a[i] % 2 == 0){
count++;
}
}
percent = (100*count/a.length);
}
System.out.println(percent);
}
}
Upvotes: 1
Reputation: 388
For a simple division like 2*100.0/5 = 40.0, the above logic would work fine but think about the situation where we have 51*100.0/83 the output would be less readable and its always advisable to truncate the percentage to a limited decimal digits.
An example:
int count = 51;
Double percent = 0.0;
int length = 83;
percent = count*100.0/length;
System.out.println(percent);
output: 61.44578313253012
When you truncate it:
Double truncatedDouble = new BigDecimal(percent ).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(truncatedDouble);
output: 61.446
Upvotes: 1
Reputation: 393856
count/a.length
returns 0
since you are dividing two ints, and the second operand is larger than the first. Change it to (double)count/a.length
in order to perform floating point division.
Alternately, change the order of operations to :
percent = 100.0*count/a.length;
Upvotes: 8