ı 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)
Related
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);
I really don't know what should be the title of this question, spent 10 minutes but this is the best I came up with.
The real question is very basic and I think I know the answer. But still, like the operator condition ? true-statement : false-statement, is there any shortcut of this kind of if statement?
if(intA == -1 || intB == -1 || intC == -1 || intD == -1 || intE == -1)
Suggestion: Something like this could be added in Java:
if((intA || intB || intC || intD || intE) == -1)
No.. There isn't. These are different variables with different values.
Suggestion: you can consider the all these variable necessary or not. If all these variables necessary there will be no way to simplify.
You should use lists for this purpose.
For ex.
You can implement function
findFirstEquals(List, Int)
which iterate through the list, search for first element that equals to second parameter and returns true if found.
In this case your if would be like following
intList = ArrayList<Int>()
// put 5, 6, 7,8 etc...
if findFirstEquals(intList, -1) ...
Afaik, there is no real shortcut syntax for this. Probably, you could do some tricks with logical and/or to achieve this, but I would not recommend to do so as it would be harder to read:
if (((intA | intB | intC) & -1) == -1)
You could still add those ints to an collection, and check if -1 is contained in that collection.
Fun fact: In Python, there is syntactic sugar for comparing a variable with 2 values; you can write 2 < a < 3, which would not be possible in Java. But personally, I do not know a language where syntactic sugar for what you are asking for exists.
You can use Switch() statement to make it more easy like below
public void myMethod(int intValue)
{
switch (intValue) {
case -1: //Your logic here ;
break;
case 1 : //Another condition
break;
default: //Default behaviour;
break;
}
}
Call method myMethod(yourValue) and passed your value to it.
Passed your integer value to switch it will handle it as per value you have passed.
May this will help you.
Can anyone help me to understand this line? I tried to transform it with "if .. else" but it didn't work. Thanks in advance.
return (patient1.isEmergencyCase() == patient2.isEmergencyCase()) ? (Integer.valueOf(patient1.getId()).compareTo(patient2.getId())) : (patient1.isEmergencyCase() ? -1 : 1);
if (patient1.isEmergencyCase() == patient2.isEmergencyCase()) {
return Integer.valueOf(patient1.getId()).compareTo(patient2.getId());
} else if (patient1.isEmergencyCase() ) {
return -1;
} else {
return 1;
}
In other words, it's a sorting, probably to decide which patient comes first. You would typically find such a code in a compareTo method, which is typically used to sort lists, in this case to define who gets "served" in which order.
It returns -1 if partient1 is "lesser/earlier/etc", which happens if both of them are emergency cases and patient1's id is lower OR if only patient1 is an emergency case, otherwise it returns 1 (or 0, is both are emergency cases and their ids are equals).
You can have a look if the concept isn't yet clear: Comparable.
if (patient1.isEmergencyCase() == patient2.isEmergencyCase()) {
return Integer.valueOf(patient1.getId()).compareTo(patient2.getId());
} else {
if (patient1.isEmergencyCase())
return -1;
else
return 1;
}
This is what has been condensed into the nested ternary expression.
The first step in understanding is to convert the expression inside the else into a ternary, and then work your way outwards.
That is,
if (patient1.isEmergencyCase())
return -1;
else
return 1;
is equivalent to return patient1.isEmergencyCase() ? -1 : 1.
But this expression itself is under the else condition.
What the code is doing is that if both patients are emergency cases, or both are non-emergency cases, then prioritize the one whose id comes first (according to the compareTo method). If, however, one patient is an emergency case while the other is not, then prioritize the emergency patient ... quite a realistic situation.
It's just like this:
if(patient1.isEmergencyCase() == patient2.isEmergencyCase()){
return Integer.valueOf(patient1.getId()).compareTo(patient2.getId());
} else {
if(patient1.isEmergencyCase()){
return -1;
} else
return 1;
}
It's a short way to write the same thing. Put the condition to evaluate before the '?' character, the put the two condition true : false.
Simple!
You should use nested if-else for producing output from this line....here multiple ternary operators are used ...
ternary operator---- condition?true statement :false statement;
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.
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"