24

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
':' excepted

I 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("§") : 
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Erik Kubica
  • 1,180
  • 3
  • 15
  • 39

6 Answers6

95

Syntax is Shown below:

"your condition"? "step if true":"step if condition fails"
Sachin
  • 3,424
  • 3
  • 21
  • 42
32

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

Community
  • 1
  • 1
Guillaume
  • 22,694
  • 14
  • 56
  • 70
29

(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("§");
Bohemian
  • 412,405
  • 93
  • 575
  • 722
Zuhair Sagga
  • 301
  • 3
  • 4
3
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.

TieDad
  • 9,143
  • 5
  • 32
  • 58
2

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.

GetBackerZ
  • 448
  • 5
  • 12
-2

This should be (condition)? True statement : False statement

Leave out the "if"

Ndivhuwo
  • 280
  • 2
  • 10
  • 4
    This question was asked and answered 3 years ago. This does not add any extra information. – George Dec 14 '16 at 14:25