0

public class questions {

public static void main(String[] args) 
{
    Scanner userInput = new Scanner (System.in);
    
    System.out.println("Enter two numbers: ");
    int num1 = userInput.nextInt() ;
    int num2 = userInput.nextInt() ;
    
  (num1==num2) ? System.out.println("Same"): System.out.println("Not same");  // i am getting an error in that line
    
}

}

how can i compare these two numbers from user inputs with the conditional operator ?

Mesut Ozil
  • 13
  • 7

3 Answers3

3

Java separates some elements of your program into statements and expressions. A statement is an instruction to do something, and an expression is code that produces some value. You can write an expression and ignore the value (Math.sin(0);), called an expression statement, but a statement on its own has no value and can't be made into an expression.

The conditional/ternary operator ?: works only on expressions; that is, it's not a general flow-control tool like if but can only be used to select between two alternate values. Since System.out.println returns void (no value), it can only be called as a statement and thus can't be used as a ternary.

You can always use if to select between entirely different statements (usually and preferably block statements); if you want to use the conditional operator with System.out.println you must use it to select an expression to be passed to it as its argument:

System.out.println(condition ? "true" : "false"); // an expression of type String
chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
1

You should assign a string response to a ternary expression with similar logic, and then print that message:

int num1 = userInput.nextInt();
int num2 = userInput.nextInt();

String msg = num1 == num2  ? "Same" : "Not same";
System.out.println(msg);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Try something like this instead:

System.out.println((num1 == num2) ? "Same" : "Not same");
Adrian Russo
  • 546
  • 4
  • 16