How to shrink my expression with a ternary operator - java

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);

Related

concatenation of variables with probability of null or 0

Ok i don't know how to exactly explain completely what my issue is i'm facing to get what i want, but the basis of what i'm trying to accomplish here is...i don't want a -> ; <- to show up if the variable is Null or 0. Something I've attempted so far is a scanner input where when you run the code it asks to input values that are > 0 and if you input one thats not it'll give an invalid input error. Im trying to find a different method where its not needed to keep repeating this method for 20 or more. Like i said im just trying to have it input the numbers automatically, and if theres no number in one of the variables it would skip it and not put another " ; " and just put the ones that do have numbers with the semicolon. So what i'm looking at to accomplish is listed in the image bellow :
I had difficulties to understand your question. I am also not an english speaking person....
If I understood you want this:
String a,b,c,d,e, all;
all = "";
if(a!=null && a!=0){
all += a;
}
if(b!=null && b!=0){
all += b;
}
if(c!=null && c!=0){
all += c;
}
...
if(all != ""){
//something
} else {
// something else
}
Note that I am not permutating, I am sequencially checking for values in each variable then performing the desired effect.... I just concatenated strings, if you want to add stuffs like (space),; (semicolon), its up to you.

Short java if else if else statement

I have a if else short statement as follows:
(one == two) ? "do this" : "do this"
Is there anyway to add an if else into this statement?
I can't seem to find anything with an if else...
I'm being specific to the short statement, as opposed to do if if else else longhand.
Thanks.
If you want to convert something like:
if(A) {
return X;
}
else if(B) {
return Y;
}
else {
return Z;
}
You can write this as:
A ? X : (B ? Y : Z);
You thus write the else if as a condition in the else-part (after :) of the upper expression.
However, I would strongly advice against too much cascading. The code becomes extremely unreadable and the ? : code structure was never designed for this.
You can extend this to any number of clauses, in perfect analogy to the if-else construct.
return a == b? "b"
: a == c? "c"
: a == d? "d"
: "x";
In this form it quite closely resembles Lisp's cond, both in shape and in semantics.
But, do note that this is not a "shorthand for if/else" because it is an expression whereas if/else is a statement. It would be quite bad abuse of the ternary operator if the expressions had any side effects.
The ":" is the else
(one == two) ? "do this" : "do that"
If one equals two then "do this", otherwise (if one not equals two) than "do that".
I sometimes use Maps for such situations:
private final static Map <String, String> codesMap = <generate the map with values>
...
codesMap.get(one)
Yes, Above statement can be written using if-else. Here Ternary operator is used.
if(one==two)
{
//Code
}
else
{
//code
}
Ternary operator reduces Line Of Code(LOC) by writing condition in one statement instead of many using "? :".
For more information please refer:
http://java.meritcampus.com/t/48/Ternary-operator?tc=mm71
http://java.meritcampus.com/t/60/If-else-if-ladder?tc=mm72
This works like an if-else-statement but technically you could convert this into an if-else-statement. That would look like this:
if (one == two) {
"do this"
} else {
"do that"
}
if your question is whether or not you could insert an if statement into
(one == two) ? "do this" : "do this" ... no, rather you should use nested if statements.

Loop through column of tableview and get cell data

I have a TableView with two Columns (let's call them A and B). I like to loop through column A and print their values to console. My code doesn't seem to work the way I want it to....
for (int i : myTable.getItems().size()) {
System.out.print(columnA.getCellData(i));
}
Suggestions?
You almost had it! But I don't think that for loop is valid - it expects an Array not an int.
for (Object o : myTable.getItems()) {
System.err.println(columnA.getCellData(o));
}
Or if you are using Java 8, this is a shorter way:
myTable.getItems().stream().forEach((o)
-> System.err.println(columnA.getCellData(o)));
This works for me.
If it doesn't just comment and I'll see what's wrong.
I just checked the code and found a small correction - the type of the item for getCellData() must be String not object. For the first example, this would result in:
for (String[] o : myTable.getItems()) {
System.err.println(columnA.getCellData(o));
}

inline if statement java, why is not working

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"

boolean operation trick

I've seen this before in code, but forgotten it. Basically it toggles a boolean variable. If it's true, it'll set to false and vice-versa. But unfortunately forgot the syntax.
It's basically a one liner for this:
if (myVar) {
myVar = false;
} else {
myVar = true;
}
It's something like this, but don't know what it's called or the correct syntax of it:
myVar = myVar : false ? true;
How about
myVar = !myVar
?
myVar = myVar ? false : true; is using the conditional operator.
You can just do this though
myVar = !myVar;
Another option is XOR:
myVar ^= true;
It's notable in that only the LHS of the assignment ever changes; the right side is constant and will toggle any boolean variable. Negation's more self-documenting IMO, though.
What you are thinking of is the conditional operator:
myVar = myVvar ? false : true;
(As you see, a lot of people call this "the ternary operator", but that only means that it is an operator with three operands. As it happens, there is only one operator with three operands in this language, but it still says nothing about what the operator does.)
It's of course easier to use the negation operator:
myVar = !myVar;
The smallest code I can think of at the moment. I don't know what its called (if it has a name, as you seem to suggest)
myVar = !myVar
What you're talking about is the "ternary" or "conditional" operator, which does an inline substitution as per a condition.
The syntax is:
condition ? trueValue : falseValue
I usually throw parentheses around my condition, sometimes around the whole conditional operator. Depends on how much I'm trying to delineate it from everything else.
So for example, suppose you want to return the larger of two numbers:
public int max(int a, int b)
{
return (a > b) ? a : b;
}
Notice that it can be substituted into the middle of something else.
Okay, now let's tackle your actual question about toggling a boolean type.
myVar = (myVar) ? false : true;
is how you would do it with the conditional operator. (Again, parentheses aren't required, I just favor them.)
But there's a simpler way to toggle the boolean... using the logical NOT ("!") operator:
myVar = !myVar;
Keep it simple. :-)
if(myVar == true)
{
myVar = false;
}
else if (myVar == false)
{
myVar = true;
}
else
{
myVar = FILE_NOT_FOUND
}
This also works :P
v=v?!v:!v;
There is a ternary operator (wikipedia). Which allows you to write a condensed if-else statement like in the second example.
In java:
myVar = (myVar) ? true : false;
There is also the NOT operator, which toggles a boolean variable. In java that is !. I believe that is what you want.
myVar = !myVar;
public boolean toggle(boolean bool)
{
return !bool;
}
I recently (on my own) found a similar answer to one already stated here. However, the simplest and shortest (non-repeating variable name with least code) answer is:
formControl.disabled ^= 1;
This works best in JavaScript when wanting to toggle boolean, DOM-based attributes (for example, a form control/input's disabled property -- going from a non-editable to edit state). After much searching (with no result that I liked) and some trial and error, I found my solution to be the simplest (however, true instead of a 1 would be clearer -- as was previously posted).
Since this syntax isn't very clear, immediately, I would not advise using it very often (I believe it is appropriate when the variable or property makes the context obvious). I have posted this response (instead of making it a comment) because the context in which the XOR bitwise self-assignment should be used is very important. This "trick" should mostly be avoided when considering best practices.
As others have noted, there are two ways to negate something: "lvalue = !lvalue;" and "lvalue ^= 1;". It's important to recognize the differences.
Saying "lvalue = !lvalue" will cause lvalue to be set to 1 if it was zero, and 0 if it was set to anything else. The lvalue will be evaluated twice; this is not a factor for simple variables, but saying "someArray[index1][index2][index3][index4] = !someArray[index1][index2][index3][index4]" could slow things down.
Saying "lvalue ^= 1;" will cause lvalue to be set to 1 if it was 0, 0 if it was 1, and something else if it was neither zero nor 1. The lvalue need only be specified or evaluated once, and if the value is known to be either zero or 1, this form is likely to be faster.
Too bad there's no auto-negate operator; there are times such a thing would be handy.
You can also use the binary form of negation as shown here.
if ((v == true) && !(v = false)) {
v != true; /* negate with true if true. */
} else {
v =! false; /* negate with false if false. */
}

Categories

Resources