inline if statement java, why is not working - java

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("§") :

Syntax is Shown below:
"your condition"? "step if true":"step if condition fails"

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

(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("§");

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.

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.

This should be
(condition)? True statement : False statement
Leave out the "if"

Related

ternary operator do nothing in else part

I have tried to leave the else part empty for ternary operator ( for int variables ), but I can't do it what is the problem?
here is the code
int FemaleCounter=0, MaleCounter =0, StateCounterIn =0 , StateCounterOut =0;
if(arr[0].equals("male") ) {
MaleCounter ++;
}
if(arr[0].equals("female") ) {
FemaleCounter ++;
}
if(arr[1].equals("in")) {
StateCounterIn++;
}
if(arr[1].equals("out") ) {
StateCounterOut++;
}
here is the ternary operator form :-
MaleCounter = arr[0].equals("male") ? MaleCounter++ : ;
FemaleCounter = arr[0].equals("female") ? FemaleCounter++ : ;
StateCounterIn = arr[1].equals("in") ? StateCounterIn++ : ;
StateCounterOut = arr[1].equals("out") ? StateCounterOut++ : ;
Thanks for your answers .
MaleCounter += arr[0].equals("male") ? 1 : 0;
FemaleCounter += arr[0].equals("female") ? 1 : 0;
StateCounterIn += arr[1].equals("in") ? 1 : 0;
StateCounterOut += arr[1].equals("out") ? 1 : 0;
A ternary expression must deliver a result. Also ++ inside and then assigment is overkill.
As its name indicates, the ternary operator takes three operands. You cannot omit any of them any more than you can omit either operand of any of the binary operators (*, /, ., etc.), or the one operand of a unary operator (++, --, among others).
The fact that an expression using the ternary operator is in some ways analogous to an if / then / else statement is irrelevant here, but the key distinction is important: an expression in the ternary operator evaluates to a value. It is necessary to designate that value for each alternative.
Observe, further, that your analogy is false anyway. You might consider fixing the syntax issue by using forms similar to this ...
// useless
MaleCounter = arr[0].equals("male") ? MaleCounter++ : MaleCounter;
..., but that does not have the same effect as your corresponding if statement, because in the case where the increment is performed, the pre-increment value is afterward assigned back to MaleCounter.
I find your original code pretty clear, but if for some reason you insist on using the ternary operator, then one of these is the model I would follow:
MaleCounter = arr[0].equals("male") ? MaleCounter + 1 : MaleCounter;
FemaleCounter += (arr[0].equals("female") ? 1 : 0);

How to shrink my expression with a ternary operator

I would love to know how to shrink this code into 1 line with a ternator operator, the idea is change the drawable of a image inside my RecyclerView when its 1 or 0, I have done this but I think is not that performant to have multiple if elses to do it, instead I know that it can be done in just 1 line with a ternary operator.
if(json.hasTime(mArrayList.get(mPosition))==1){
mHolder.imageEvent.setImageResource(R.drawable.ic_event_black_24dp);
}else{
mHolder.imageEvent.setImageResource(R.drawable.ic_event_busy_black_24dp);
}
I want to do something like this :
(if 1 or 0 ? value 1 : value2 );
Try this :
mHolder.imageEvent.setImageResource(json.hasTime(mArrayList.get(mPosition))==1 ? R.drawable.ic_event_black_24dp : R.drawable.ic_event_busy_black_24dp);
You can always convert expressions from (1) to (2) like so,
//(1)
if(condition){
stmt1;
}else{
stmt2;
}
//(2)
somevariable = condition?stmt1:stmt2;
So your single line expression can be written as follows,
mHolder.imageEvent.setImageResource(json.hasTime(mArrayList.get(mPosition))==1?R.drawable.ic_event_black_24dp:R.drawable.ic_event_busy_black_24dp);
Something like this.
mHolder.imageEvent.setImageResource(json.hasTime(mArrayList.get(mPosition))==1?
R.drawable.ic_event_black_24dp : R.drawable.ic_event_busy_black_24dp)
Try this:
json.tieneHora(mArrayList.get(mPosition))==1?mHolder.imageEvent.setImageResource(R.drawable.ic_event_black_24dp):mHolder.imageEvent.setImageResource(R.drawable.ic_event_busy_black_24dp);

How to write nested ?: statements

I would like to shorten my code by the use of the ?: (if-else-then) comparative operator instead of using the traditional if{}else{} blocks that inconveniently tend to take over the screen. I was never taught about this operator, and I would greatly appreciate any help regarding how to nest multiple comparisons within one line.
This is the code that I would like to shorten:
if(y<0)
y=0;
else
if(y+h>s.getHeight())
y = s.getHeight()-h;
I managed to condense each condition to this (not nested):
y = (y<0) ? 0 : y;
y = (y+h>s.getHeight()) ? s.getHeight()-h : y;
Is this the correct way to nest it?
y = (y<0) ? 0 : ((y+h>s.getHeight()) ? s.getHeight()-h : y);
Thank you!
EDIT: I was given a link to another post pertaining to the ?: operator. Link. However, my question has to do with nesting instead of just a simple if statement. Therefore, my question is not a duplicate of that post.
Yes, this is correct syntax but it's not readable.
You can check by yourself this in Java. Like this:
int a = 3;
int b = 5;
String s = (a < b) ? "Less than b" : (a > b) ? "More than b" : "Equal as b";
System.out.println(s);
But code is much more readable if you use if and if else statements. This ? and : is just for basic if statement.
For example:
int a = 3;
int b = 5;
String s = (a == b) ? "Equal" : "Not equal"
System.out.println(s);
But even in this case, I would rather use if statement. I really don't like to see ? and : instead of if statement :)
Regards,
golobic
You have correctly used ternary operator. However you could have avoided repeated method invocations for s.getHeight().
y = y < 0 ? 0 : y+h > s.getHeight() ? s.getHeight() - h : y;
Use the ?: (ternary) operator instead of an if-then-else statement if that makes code more readable.
ex. result = someCondition ? value1 : value2;
This can be nested further if value1, value2 are also ternary expressions.

Compere if statement short form

ı want to use short form for if statement. How can ı write if statement at one line? and how can ı compare them ı know there is same question at here. but my statement do not have else so ı could not do it without else statement.
public int compareTo(Uyum u) {
if (uyum < u.uyum)
return -1;
if (uyum > u.uyum)
return 1;
return 0;
}
You can use a ternary operator :
return uyum < u.uyum ? -1
: uyum > u.uyum ? 1
: 0;
You perhaps want:
return a < b ? -1 : (a > b ? 1 : 0);
you may simply write this:
public int compareTo(Uyum u) {
return uyum - u.uyum;
}
Inline if statement (question mark) are normally only desired if you have two states. Readability of your code is very important.
In your case you have 3 states (0, 1 and -1); I would not recommend using the inline if statement.
Example inline if statement:
String value = variable==null?"defaultvalue":variable;
This if statement notation is called ternary operator
It seems to me that u.uyum is an int, in which case, why is the following not satisfactory?
return Integer.compare(uyum, u.uyum)
If you really must use a ternary operator, you can do as everybody else is suggesting:
return uyum > u.uyum ? 1 : uyum == u.uyum ? 0 : -1
This tends to be frowned upon though, as it's not terribly legible.
return (uyum-u.uyum)==0?0:((uyum-u.uyum)<0?-1:1)

Question mark in java code

Can someone explain the question mark in the following code? Also INITIAL_PERMANCE is a static final constant in the code but what is the last line of synatax called?
Synapse(AbstractCell inputSource, float permanence) {
_inputSource = inputSource;
_permanence = permanence==0.0 ?
INITIAL_PERMANENCE : (float)Math.min(1.0,permanence);
}
The ? and : are part of the java conditional operator. Sometimes called the ternary operator because it is the only operator in Java that takes 3 arguments.
This is essentially an inline IF / THEN / ELSE block.
_permanence = permanence==0.0 ?
INITIAL_PERMANENCE : (float)Math.min(1.0,permanence);
Can be rewritten as follows:
if (permanence == 0.0)
_permanence = INITIAL_PERMANENCE;
else
_permanence = (float) Math.min(1.0,permanence);
The general form of the conditional operator is
<Test returning a boolean> ? <value for if test is true> : <value for if test is false>
It's called the Java ternary operator (as Hovercraft said), and is used like this:
type variableName = (statement) ? value if statement is true: value if false;
This is the most common way it is used.
[Optional Variable] = ( Boolean Test ) ? (Execute this if True) : (Execute this if false)
This is the ternary operator. It works like an if-else statement.
Decomposed, the statement is similar to this:
if(permanence == 0.0) {
_permanence = INITIAL_PERMANENCE;
} else {
_permanence = (float)Math.min(1.0,permanence);
}
Its use is limited in situations in which the meaning is very clear. Ternary operators can confuse, so use them sparingly.
The last statement:
(float)Math.min(1.0, permanence)
is called a type cast. You're casting the result of Math.min(), which returns a double, to that of a float. You'll have to read up more on what floating point numbers are to see the value of doing that is.
This is equal to an if else statement in an inlined manner.Equivalent to
_permanence =
{// A kind of anonymous routine for assignment
if(permanence==0.0)
{ INITIAL_PERMANENCE }
else
{ (float)Math.min(1.0,permanence)}
}
A good explanation is on oracle site about ternary operators

Categories

Resources