Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad operand type int for unary operator '! in while statement

Tags:

java

import java.util.Scanner;
public class GuessingGame_v1
{
    public static void main(String[] args)
    {
        double randNum = Math.random();

        int number =(int) (randNum * 100.0);
        int counter = 0;
        Scanner in = new Scanner(System.in);

        int guess = 0;

        while (!guess = randNum)
        {
            System.out.println("Enter your guess: ");
            int guess = in.nextInt();

           if(guess > randNum)
               System.out.println("Too High");
           else
               System.out.println("Too Low");
        }    
        if (guess = randNum)
            System.out.println("Congradulations you guessed the number!");
    }
}

I am new to code but on this code it keeps saying "bad operand type int for unary operator '!'. What can I do to fix this?

like image 265
Hunter Gay Avatar asked Dec 25 '22 12:12

Hunter Gay


1 Answers

! is an unary negation operator that expects a single boolean operand. Therefore it can't be applied on an int.

You should change

while (!guess = randNum)

to

while (guess != randNum)

!= is the operator that checks whether two numbers are not equal to each other.

In addition

if (guess = randNum)

should be

if (guess == randNum)

since you want to compare the numbers (and not to assign randNum to the guess variable).

like image 72
Eran Avatar answered Feb 17 '23 17:02

Eran