inline if statement java, why is not working
Solution 1
The ternary operator ? :
is to return a value, don't use it when you want to use if
for flow control.
if (compareChar(curChar, toChar("0"))) getButtons().get(i).setText("§");
would work good enough.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Solution 2
Syntax is Shown below:
"your condition"? "step if true":"step if condition fails"
Solution 3
(inline if) in java won't work if you are using 'if' statement .. the right syntax is in the following example:
int y = (c == 19) ? 7 : 11 ;
or
String y = (s > 120) ? "Slow Down" : "Safe";
System.out.println(y);
as You can see the type of the variable Y is the same as the return value ...
in your case it is better to use the normal if statement not inline if as it is in the pervious answer without "?"
if (compareChar(curChar, toChar("0"))) getButtons().get(i).setText("§");
Solution 4
Your cases does not have a return value.
getButtons().get(i).setText("§");
In-line-if is Ternary operation all ternary operations must have return value. That variable is likely void and does not return anything and it is not returning to a variable. Example:
int i = 40;
String value = (i < 20) ? "it is too low" : "that is larger than 20";
for your case you just need an if statement.
if (compareChar(curChar, toChar("0"))) { getButtons().get(i).setText("§"); }
Also side note you should use curly braces it makes the code more readable and declares scope.
Solution 5
cond? statementA: statementB
Equals to:
if (cond)
statementA
else
statementB
For your case, you may just delete all "if". If you totally use if-else instead of ?:. Don't mix them together.
Erik Kubica
PHP, ReactJS & JavaScript, Flutter developer with light skills of Java, C#
Updated on May 23, 2020Comments
-
Erik Kubica almost 4 years
Desc: compareChar returns true or false. if true it sets the value of button, if false do nothing.
I am trying to use:
if compareChar(curChar, toChar("0")) ? getButtons().get(i).setText("§");
netbeans is saying:
')' excepted
':' exceptedI tried these combinations:
if compareChar(curChar, toChar("0")) ? getButtons().get(i).setText("§"); if compareChar(curChar, toChar("0")) ? getButtons().get(i).setText("§") : ; if compareChar(curChar, toChar("0")) ? getButtons().get(i).setText("§") : if (compareChar(curChar, toChar("0"))) ? getButtons().get(i).setText("§"); if (compareChar(curChar, toChar("0"))) ? getButtons().get(i).setText("§") : ; if (compareChar(curChar, toChar("0"))) ? getButtons().get(i).setText("§") :
-
George over 7 yearsThis question was asked and answered 3 years ago. This does not add any extra information.