In: Computer Science
Write a method that returns the percentage of the number of elements that have the value true in an array booleans.
SOLUTION -
CODE -
//java code
import java.lang.Math;
public class pT{
public static float percentTrue(boolean[]
a){
float ct, pt;
ct = 0;
pt = 0;
if(a.length == 0){
System.out.println("Array is empty");
}
else{
for(int i = 0; i < a.length; i++){
if(a[i] == true)ct = ct + 1;
}
pt = ct/a.length * 100;
}
return pt;
}
public static void main(String
[]args){
boolean[] array =
{true, false, true, false, false, false, true};
System.out.print("The elements are ");
for(int i = 0; i
< array.length; i++){
System.out.print(array[i] + " ");
}
System.out.println("\nThe percentage of elements having the value
true is " + Math.round(percentTrue(array) * 10) / 10.0 +
"%");
}
}
Output:
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I
WILL SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------