The `If statement ` in JGrasp

2.1k Views Asked by At

How do I change the code....

if (yourAnswer = numberOne + numberTwo)
{
   System.out.println("That is correct!");
   counter = counter + 1;
}
else
{
   System.out.println("That is incorrect!");
}

This does not seem to be working for me. Can anyone help me?. The debugger is saying:

RandomNumbersProgramThree.java:21: error: incompatible types: int cannot be converted to boolean".

2

There are 2 best solutions below

0
On

You cannot associate a number with a Boolean value. A boolean is true or false, not a number, however you can create a variable that indicates if a certain number represents true or false. Is this your entire program? I would like to see what "yourAnswer", "numberOne", and "numberTwo" are stored. but for now I will write a pseudo-program to explain the theory.

   import java.util.*;
   public class ExampleProgram
    {
   public static void main(String[] args)
     {
     System.out.println("Please enter two numbers");
     Scanner answer = new Scanner (System.in);

     int yourAnswer = answer.nextInt();
     int numberOne = 1;
     int numberTwo = 2;


     if (yourAnswer == (numberOne + numberTwo))
     {
        System.out.println("That is correct!");
     }
     else
     {
        System.out.println("That is incorrect!");
     }
  }
}

This program will ask the user to input a number, for example the number "3". It will then compare that number to the two numbers you declares, "numberOne" which equals the value of one, and "numberTwo" which equals the value of two. Therefore, in the "IF" statement it says, "If (yourAnswer == (numberOne + numberTwo))" which means that 1 + 2 = 3, if the users answer is 3, then 3 = 3 and the result will come back as true.

0
On

In the if statement, you are using an '=' sign, this type of equal sign is not a comparison '=' but is used to set a value to an variable. ie, int x = 2; The type of equals you need is the type that is used in comparisons, which is ==. You always use == when dealing with boolean comparisons