How to fix my output of number of runs

I want to print out how many times Math.random() was less that 0.5 and how many thimes it was bigger that 0.5. So I use int sum variable and increase it each time as you can see in the code:

package shapes;

public class Main {


public static void main(String[] args) {

    for (int i=1; i<6; i++){
    int sum1=0;
    if(Math.random()<0.5){
         System.out.println("head");
         System.out.println(Math.random());
         sum1++;
         System.out.println("sum of head"+sum1);

     }else {
         int sum2=0;
         System.out.println("tail");
         System.out.println(Math.random());
         sum2++;
         System.out.println("sum of tail"+sum2);
        }
    }

    }

            }

My output is :

tail
0.2420579681161944
sum of tail1
head
0.712979930711983
sum of head1
tail
0.28072067461911476
sum of tail1
head
0.5897197845744805
sum of head1
head
0.6735600614954825
sum of head1

I want the output to be like this :

tail
0.2420579681161944
head
0.712979930711983
tail
0.28072067461911476
head
0.5897197845744805
head
0.6735600614954825
sum of head 3 
sum of tail 2

I actually tried to put sum1++ and sum2++ in different places but did not worked . thanks

Answer

You reset sum to 0 each time in the for loop. Move your sums variable declaration out of the loop.

int sum1=0;
int sum2=0; 
for (int i=1; i<6; i++){
double val = Math.random();    
if(val<0.5){
     sum1++;
 }else {
     sum2++;
    }
     System.out.println("sum of head "+sum1);
     System.out.println("sum of tail "+sum2);    
 }

Leave a Reply

Your email address will not be published. Required fields are marked *