I get "The mismatch type cannot convert from int to boolean", despite not using a boolean

I am doing an exercise in the book "Java, How to Program." I have to make an application that simulates fraud. I have to make a method (flip) that accidentally returns the side for the coin. I decided to make the method return 1 or 2, and in the main method "convert" the values ​​to 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 only work with integers, and I don’t see how logical lines arise.

The code is as follows:

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; } } 
+4
source share
5 answers

Your code

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

Must be

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

You assign an int type to coinValue and evaluates to bool inside the if statement.

+14
source

Instead of comparison operators (equality ==), if use the assignment operator (=):

 if (coinValue = 1) 

Must be

 if (coinValue == 1) 

The if statement expects a Boolean expression, you assign 1 to coinValue , and then try to interpret this as a boolean to handle the conditional.

+6
source

This is one of the most common and dangerous programming errors that developers make. In the old days, compilers (for example, the C compiler) would not complain about the if(coinValue = 1) , since it would affect coinValue by 1 and always evaluate the condition to true, since it is 1 . Fortunately, the Java compiler catches this error and prevents you from doing this. As stated in the answers above, change if (coinValue = 1) to if (coinValue == 1) and your problem should be fixed.

+1
source

I ran into this b / c error I had i = 4 in the for ie statement "for (i = 1; i = 4; i ++) ...."

you cannot use a value equal to "=" in the for command for a stop value.

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

instead

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

with two equal signs

0
source

Source: https://habr.com/ru/post/1386475/


All Articles