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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With