Home > database >  Operator && cannot be applied to operands of type 'int' and 'bool'
Operator && cannot be applied to operands of type 'int' and 'bool'

Time:10-27

This program is guessing a number from a dice (1,6) User vs Enemy Computer. So my problem is if the User guess and Computer guess are correct. But i'm stuck at the Operator && cannot be applied to operands.

class Program
{
    static void Main(string[] args)
    {
        bool isCorrectGuess = false;
        Random random = new Random();

        int enemyRandomNum;

        int randomNum = random.Next(1, 6);

        Console.WriteLine("Welcome to the dice number guessing game!");
        Console.WriteLine("A number between 1 and 6 will be generated.");
        Console.WriteLine("Who guess the correct number will have   1 point.");
        Console.WriteLine("---------------------------------------------------");

        while(!isCorrectGuess)
        {
            Console.WriteLine("Please enter your guess.");
            int playerGuess = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("...");
            System.Threading.Thread.Sleep(1000);

            Console.WriteLine("Enemy AI will now have a guess. ");

            Console.WriteLine("...");
            System.Threading.Thread.Sleep(1000);

            enemyRandomNum = random.Next(1,6);
            Console.WriteLine("Enemy AI rolled "   enemyRandomNum);

            // here is the error

            if (playerGuess && enemyRandomNum > randomNum)
            {

            }


        }


    }
}

CodePudding user response:

This:

if (playerGuess && enemyRandomNum > randomNum)

Semantically means:

If playerGuess is true
and
enemyRandomNum is greater than randomNum

But playerGuess can't be true because it's not a boolean, it's an integer. If you want to test is both of these values are greater than randomNum then you need to specify that:

if (playerGuess > randomNum && enemyRandomNum > randomNum)

CodePudding user response:

playerGuess is an integer but you treat it as a bool. Try something like

(playerGuess > 0) && (enemyRandomNum > randomNum)

Another solution is that you can convert playerGuess to a bool. Try

bool b = Convert.ToBoolean(playerGuess);

or

bool b = playerGuess != 0;
  •  Tags:  
  • c#
  • Related