简体   繁体   中英

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

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?

! 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM