0

I want to use ? : expression instead of if with 4 conditions in this code but i dont know how< any answers please?

import java.util.Scanner;
public class Ex13 {
  public static void main(String[] args) {
    Scanner e = new Scanner(System.in);
     int x, y, sum, diff;
     boolean z = false;
     System.out.println("Enter x and y");
     x = e.nextInt();
     y = e.nextInt();
     sum = x+y;
     diff = x-y;
     if(x==15||y==15||sum==15||diff==15){
                        z=true;
                       }
      System.out.println(z);
    }}

i tried using else if else if, and i tried ? : but there was a problem with the lossy conversion from boolean to in types.

4
  • Show the code you tried that didn't work, and the specific error it caused. Stack Overflow questions are best when they're about the specific thing that went wrong, as opposed to about the larger task you intended to accomplish when that thing went wrong. Commented May 18, 2024 at 11:50
  • 2
    What is the question: how to use ? :, or why the "lossy conversion"? And what "conversion from boolean to in"? (BTW the code could be simplified to z = x==15 || y==15 || sum==15 || diff==15; no need for if or ? : - the expression/condition is already resulting in a boolean) Commented May 18, 2024 at 11:51
  • Sometimes code has not-simple conditionals in it. The one you have is really not that difficult to understand. Commented May 18, 2024 at 11:57
  • Ternary operator ?: doesn't replace if-else condition. It is used for inline evaluation of expression which returns a boolean value. Commented May 18, 2024 at 12:59

1 Answer 1

2

I prefer the way you have your if statement right now, but if you really wanted to use a ternary expression, you could try:

z = (x == 15 || y == 15 || sum == 15 || diff == 15) ? true : false;

But appreciate that in your particular code snippet, the assignment value happens to be identical to the boolean expression in the if statement, so you could just use a direct assignment:

z = (x == 15 || y == 15 || sum == 15 || diff == 15);
Sign up to request clarification or add additional context in comments.

1 Comment

And especially in the latter case, z would not need to be initialized to false. Just start the assignment with boolean z =

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.