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;
}
}
Your code
Should be
You’re assigning an int type to coinValue and that is being evaluated as a bool inside the if statement.