Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

/* Method that returns the percentage of array elements having the value true *

ID: 3573542 • Letter: #

Question

/* Method that returns the percentage of array elements having the value true
*
*/

import java.text.DecimalFormat;

public class PercentTrue
{
public static void main( String [] args )
{
    boolean [] array = { true, false, true, false, false, false, true };
    DecimalFormat percent = new DecimalFormat( "#0.0%" );

    System.out.print( "The elements are " );
    for ( int i = 0; i < array.length; i++ )
       System.out.print( array[i] + " " );
    System.out.println( );

    System.out.println( "The percentage of elements having the value true is "
                         + percent.format( percentTrue( array ) ) );
}

// Insert your code here

}

Explanation / Answer

Use the below code to find the percentage of true in the array:

public static double percentTrue(boolean array[]){

   double truenos=0;//variable for storing the number of true values in the array . reason for making this variable double is that when you divide then quotient is given which would be zero if declare this variable as int.
   for(int i=0;i<array.length;i++){
       if(array[i]==true)
           truenos++;

// Traverse the array and compare if the value is true or not. if yes then increase the count of the variable by one
   }
  

// return the dividend obtained by dividing teh number of true by the total number of elements in the array.
   return (truenos/array.length);
}

Thank you for the question . Do let me know if you feel there is a doubt in the same :) :).