Ask Question
8 July, 13:07

Find and fix the error in the if-else statement. import java. util. Scanner;

public class NumberChecker {

public static void main (String [] args) {

int userNum;

Scanner scnr = new Scanner (System. in);

userNum = scnr. nextInt (); / / Program will be tested with values: 0, 1, 2, 3.

if (userNum = 2) {

System. out. println ("Num is equal to two");

}

else {

System. out. println ("Num is not two");

}

}

}

+3
Answers (2)
  1. 8 July, 16:11
    0
    The error generated when the code is compiled:

    incompatible types: int cannot be converted to boolean

    Explanation:

    This error is generated because the variable userNum is being assigned the value of 2.

    userNum = 2

    here = is the assignment operator used to assign the value 2 to the variable userNum

    But here we need to compare the values with the value 2. So in order to compare the values in IF statement, = = is used which is called the equality operator, instead of =

    So the corrected if statement is:

    if (userNum==2)

    So the program prompts the user to enter a value (0,1,2,3) which is read in the userNum. Next the if statement checks if that input value is equal to 2. Num is equal to two message is displayed in the output when the if condition evaluates to true and Else part is executed if the condition evaluates to false and Num is not two message is displayed in the output.

    For example the user enters a value 1 then the following message will be displayed in the output:

    Num is not two

    If the user enters 2 then the following message will be displayed in the output:

    Num is equal to two
  2. 8 July, 16:48
    0
    Hi there Rumanruxi! The error is in the if statement "if (userNum = 2) ".

    Explanation:

    The if statement in this Java code is assigning userNum the value of 2 instead of comparing it with the value of 2. For equals comparison we need to write two equals "==" in the statement as: "if (userNum = = 2) ". This will return true if userNum is 2 otherwise it will return false.
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Find and fix the error in the if-else statement. import java. util. Scanner; public class NumberChecker { public static void main (String ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers