Thursday, July 21, 2022

[FIXED] How to covert this int to boolean?

Issue

Im new to this and im having trouble with this error converting int to boolean.

public class HeadsOrTails {

    public static void main(String[] args) {
        int Heads = 0;
        int Tails = 0;
        
        for(long simulation = 1; simulation <= 2000000; simulation += 1)
        {
            int FlipResult = FlipCoin();
            if(FlipResult = 1)
            {
                Heads +=1;
            }
            else if(FlipResult = 0)
            {
                Tails += 1;
            }
        }
        System.out.println("Numer of heads appeared: " + Heads);
        System.out.println("Numer of tails appeared: " + Tails);
    }
    private static int FlipCoin() 
    {
        return (int) (Math.random() + 0.5);
    }

}

enter image description here

enter image description here


Solution

In the if condition use == operator, change your if condition to

if(FlipResult == 1){
    Heads +=1;
}
else if(FlipResult == 0){
    Tails += 1;
}

Currently you are trying to assign the value, which will give this error "int cannot be converted to boolean"



Answered By - shri_world
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.