'Java operator + & <= is undefined for the argument type(s) double, boolean [closed]
Hi I am struggling with following Task.Can someone explain me how to solve this at a beginner level
Given:
- Initialize the variables with the specified values! Use the int for integer values and double for fractional values.
- Supplement the code accordingly. The sequence and the comments in println should not be changed.
int k = -2, x = 9, y = 4, z = -2;
double a = 5.5, b = 9.4, c = -5.2;
boolean xx = false;
System.out.println("a < b <= c : " + xx);
System.out.println("x!=y and z > 0 : " + xx);
System.out.println("x > y or 0 < k < 100 : " + xx);
Expected Result
a < b <= c : false
x!=y and z > 0 : false
x > y or 0 < k < 100 : true
Whatever I try, a.e. following, I get the operator error (between bool & int or bool & double)
System.out.println("a < b <= c : " + a < b <= c);
System.out.println("a < b <= c : " + (a < b <= c));
Solution 1:[1]
In Java you can't chain operators. Operators are evaluated one at a time and each operator results in a boolean value which you would then compare to an integer.
a < b <= c here it evaluates a < b first which is true and then it tries to evaluate true <= c which doesn't work as its different datatypes. In addition, parentheses are helpful with && (and) and || (or) operators
int k = -2, x = 9, y = 4, z = -2;
double a = 5.5, b = 9.4, c = -5.2;
System.out.println("a < b <= c : " + ((a < b) && (b <= c)));
System.out.println("x!=y and z > 0 : " + ((x != y) && (z > 0)));
System.out.println("x > y or 0 < k < 100 : " + ((x > y) || (0 < k && k < 100)));
For further reading on operators and their precedence, have a read here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | XtremeBaumer |
