Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I get "Type mismatch cannot convert from int to boolean" despite not using boolean

Tags:

java

I am doing an excercise in the book "Java how to program". I am supposed to make an application that simulates coin-tossing. I am supposed to make a method (flip) which returns randomly a side for the coin. I have desided to make the method return either 1 or 2, and in the main-method I "convert" the values to mean one of the sides of the coin. The problem is that I get an error message that says: "Type mismatch -cannot convert from int to boolean". I really think that I am operating only with integers all the way, and canot see how the booleans come in.

The code is the following:

import java.util.Random;

public class Oppgave629 
{

    public static void main(String[] args) 
    {
        int command = 1;
        int heads = 0;
        int tails = 0;
        while (command != -1)
        {
            System.out.print("Press 1 to toss coin, -1 to exit:");
            int coinValue = flip();
            if (coinValue = 1) {System.out.println("HEADS!"); heads++;}
            if (coinValue = 2) {System.out.println("TAILS!"); tails++;}
            System.out.printf("Heads: %d", heads); System.out.printf("Tails: %d", tails);
        }
    }

    static int flip()
    {
        int coinValue;
        Random randomValue = new Random();
        coinValue = 1 + randomValue.nextInt(2);
        return coinValue;
    }
}
like image 584
user820913 Avatar asked Dec 15 '11 09:12

user820913


2 Answers

Your code

if (coinValue = 1) {System.out.println("HEADS!"); heads++;}
if (coinValue = 2) {System.out.println("TAILS!"); tails++;}

Should be

if (coinValue == 1) {System.out.println("HEADS!"); heads++;}
if (coinValue == 2) {System.out.println("TAILS!"); tails++;}

You're assigning an int type to coinValue and that is being evaluated as a bool inside the if statement.

like image 51
b3h47pte Avatar answered Sep 30 '22 05:09

b3h47pte


You're using an assignment (=) operator instead of a comparison operator (equality ==) in your if statements:

if (coinValue = 1)

Should be

if (coinValue == 1)

An if statement expects a boolean expression, you're assigning 1 to coinValue and it's then trying to interpret this as a boolean to process the conditional.

like image 26
Matt Lacey Avatar answered Sep 30 '22 06:09

Matt Lacey