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.
Related
I'm new to java and I was wondering if there was an easier way to write
if(a == 10 || b == 10){
//stuff
}
In my mind I tried something like this:
if(a||b == 10){
//stuff
}
because IMO that makes a lot of intuitive sense, but it's not a thing.
if you're only comparing a few values then you might as well proceed with the current approach as there is nothing in place to make it shorter. However, if you're repeating your self many times, then you can create a helper function to do the work for you.
i.e
static boolean anyMatch(int comparisonValue, int... elements){
return Arrays.stream(elements)
.anyMatch(e -> e == comparisonValue);
}
then call it like so:
if(anyMatch(10, a, b)){ ... }
That's not going to work like that. You're checking the value of two variables against a value, which ends up being two checks, if(a == 10 || b == 10).
However, you can modify this check to this code:
if(Arrays.asList(a,b).contains(10))
It results in the same behavior, but this is neither shorter nor easier to read.
Yeah turns out there isn't a way to make it shorter.
No, we can't do it because in case of java, there is no option for comparison of variables like that.
Even you couldn't write like this
if(a||b){ //staff }
but if you would write then you will get this error message
error: bad operand types for binary operator '||'
Not shorter, but more "intuitively" readable:
boolean condA = (a == 10);
boolean condB = (b == 10);
if(condA || condA){
//stuff
}
always keep in mind, the goal isn't to write shortest possible code, but best maintainable code.
I'm a beginner in coding. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code:
System.out.println("Hello, what's our name? My name is " + answer4);
String a = scanner1.nextLine();
System.out.println("Ok, Hello, " + a + ", how was your day, good or bad?");
String b = scanner2.nextLine();
**if (b.equals("good"))** { //1
System.out.println("Thank goodness");
} else **if (b.equals("it was good"))** { //2
System.out.println("Thank goodness");
} else **if (b.equals("bad"))** { //3
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
} else **if (b.equals("it was bad"))**{ //4
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
if(age<18){System.out.println("How was school?");}
else if (age>=18){System.out.println("How was work?");}
The conditions of the if statements are in Bold (surrounded with **). In case of first and the second condition I want my application to do same thing. Similarly third and fourth condition. I thought it was possible to somehow group them in if statement.
I tried with below code but it doesn't compile:
if (b.equals("good"), b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad"),(b.equals("it was bad"))) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
Can someone correct it for me?
You can use logical operators to combine your boolean expressions.
&& is a logical and (both conditions need to be true)
|| is a logical or (at least one condition needs to be true)
^ is a xor (exactly one condition needs to be true)
(== compares objects by identity)
For example:
if (firstCondition && (secondCondition || thirdCondition)) {
...
}
There are also bitwise operators:
& is a bitwise and
| is a bitwise or
^ is a xor
They are mainly used when operating with bits and bytes. However there is another difference, let's take again a look at this expression:
firstCondition && (secondCondition || thirdCondition)
If you use the logical operators and firstCondition evaluates to false then Java will not compute the second or third condition as the result of the whole logical expression is already known to be false. However if you use the bitwise operators then Java will not stop and continue computing everything:
firstCondition & (secondCondition | thirdCondition)
Here are some common symbols used in everyday language and their programming analogues:
"," usually refers to "and" in everyday language. Thus, this would translate to the AND operator, &&, in Java.
"/" usually refers to "or" in everyday language. Thus, this would translate to the OR operator, ||, in Java.
"XOR" is simply "x || y but both cannot be true at the same time". This translates to x ^ y in Java.
In your code, you probably meant to use "or" (you just used the incorrect "incorrect solution" :p), so you should use "||" in the second code block for it to become identical to the first code block.
Hope this helped :)
You're looking for the "OR" operator - which is normally represented by a double pipe: ||
if (b.equals("good") || b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad") || b.equals("it was bad")) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
This is probably more answer than you need at this point. But, as several others already point out, you need the OR operator "||". There are a couple of points that nobody else has mentioned:
1) If (b.equals("good") || b.equals("it was good")) <-- If "b" is null here, you'll get a null pointer exception (NPE). If you are genuinely looking at hard-coded values, like you are here, then you can reverse the comparison. E.g.
if ("good".equals(b) || "it was good".equals(b))
The advantage of doing it this way is that the logic is precisely the same, but you'll never get an NPE, and the logic will work just how you expect.
2) Java uses "short-circuit" testing. Which in lay-terms means that Java stops testing conditions once it's sure of the result, even if all the conditions have not yet been tested. E.g.:
if((b != null) && (b.equals("good") || b.equals("it was good")))
You will not get an NPE in the code above because of short-circuit nature. If "b" is null, Java can be assured that no matter what the results of the next conditions, the answer will always be false. So it doesn't bother performing those tests.
Again, that's probably more information than you're prepared to deal with at this stage, but at some point in the near future the NPE of your test will bite you. :)
You can have two conditions if you use the double bars(||). They mean "Or". That means only ONE of your conditions has to be true for the loop to execute.
Something like this:
if(condition || otherCondition || anotherCondition) {
//code here
If you want all of conditions to be true use &&. This means that ALL conditions must be true in order for the loop to execute. if any one of them is false the loop will not execute.
Something like this:
if(condition && otherCondition && anotherCondition) {
//code here
You can also group conditions, if you want certain pairs of them to be true. something like:
if(condition || (otherCondition && anotherCondition)) {
//code here
There is a simpler way.
if (b.contains("good")) {
...
}
else if (b.contains("bad")) {
...
}
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 have a method that checks all of the combinations of 5 different conditions with 32 if-else statements (think of the truth table). The 5 different letters represent methods that each run their own regular expressions on a string, and return a boolean indicating whether or not the string matches the regex. For example:
if(A,B,C,D,E){
}else if(A,B,C,D,!E){
}else if(A,B,C,!D,!E){
}...etc,etc.
However, it is really affecting the performance of my application (sorry, I can't go into too many details). Can anyone recommend a better way to handle such logic?
Each method using a regular expression looks like this:
String re1 = "regex here";
Pattern p = Pattern.compile(re1, Pattern.DOTALL);
Matcher m = p.matcher(value);
return m.find();
Thanks!
You can try
boolean a,b,c,d,e;
int combination = (a?16:0) + (b?8:0) + (c?4:0) + (d?2:0) + (e?1:0);
switch(combination) {
case 0:
break;
// through to
case 31:
break;
}
represent each condition as a bit flag, test each condition once, and set the relevant flag in a single int. then switch on the int value.
int result = 0;
if(A) {
result |= 1;
}
if(B) {
result |= 2;
}
// ...
switch(result) {
case 0: // (!A,!B,!C,!D,!E)
case 1: // (A,!B,!C,!D,!E)
// ...
}
All the above answers are wrong, because the correct answer to an optimisation question is: Measure! Use a profiler to measure where your code is spending its time.
Having said that, I'd be prepared to bet that the biggest win is avoiding compiling the regexes more than once each. And after that, as others suggested, only evaluate each condition once and store the results in boolean variables. So thait84 has the best answer.
I'm also prepared to bet jtahlborn and Peter Lawrey's and Salvatore Previti suggestions (essentially the same), clever though they are, will get you negligible additional benefit, unless you're running on a 6502...
(This answer reads like I'm full of it, so in the interests of full disclosure I should mention that I'm actually hopeless at optimisation. But measuring still is the right answer.)
Without knowing more details, it might be helpful to arrange the if statements in such a way that the ones which do the "heavy" lifting are executed last. This is making the assumption that the other conditionals will be true thereby avoiding the "heavy" lifting ones all together. In short, take advantage of short-circuits if possible.
Run the regex once for each string and store the results in to booleans and just do the if / else on the booleans instead of running the regex multiple times. Also, if you can, try to re-use a pre-compiled version of your regex and re-use this.
One possible solution: use a switch creating a binary value.
int value = (a ? 1 : 0) | (b ? 2 : 0) | (c ? 4 : 0) | (d ? 8 : 0) | (e ? 16 : 0);
switch (value)
{
case 0:
case 1:
case 2:
case 3:
case 4:
...
case 31:
}
If you can avoid the switch and use an array it would be faster.
Maybe partition it into layers, like so:
if(A) {
if(B) {
//... the rest
} else {
//... the rest
}
} else {
if(B) {
//... the rest
} else {
//... the rest
}
}
Still, feels like there must be a better way to do this.
I have a solution with EnumSet. However it's too verbose and I guess I prefer #Peter Lawrey's solution.
In Effective Java by Bloch it's recommended to use EnumSet over bit fields, but I would make an exception here. Nonetheless I posted my solution because it could be useful for someone with a slightly different problem.
import java.util.EnumSet;
public enum MatchingRegex {
Tall, Blue, Hairy;
public static EnumSet<MatchingRegex> findValidConditions(String stringToMatch) {
EnumSet<MatchingRegex> validConditions = EnumSet.noneOf(MatchingRegex.class);
if (... check regex stringToMatch for Tall)
validConditions.add(Tall);
if (... check regex stringToMatch for Blue)
validConditions.add(Blue);
if (... check regex stringToMatch for Hairy)
validConditions.add(Hairy);
return validConditions;
}
}
and you use it like this:
Set<MatchingRegex> validConditions = MatchingRegex.findValidConditions(stringToMatch);
if (validConditions.equals(EnumSet.of(MatchingRegex.Tall, MathchingRegex.Blue, MatchingRegex.Hairy))
...
else if (validConditions.equals(EnumSet.of(MatchingRegex.Tall, MathchingRegex.Blue))
...
else if ... all 8 conditions like this
But it would be more efficient like this:
if (validConditions.contains(MatchingRegex.Tall)) {
if (validConditions.contains(MatchingRegex.Blue)) {
if (validConditions.contains(MatchingRegex.Hairy))
... // tall blue hairy
else
... // tall blue (not hairy)
} else {
if (validConditions.contains(MatchingRegex.Hairy))
... // tall (not blue) hairy
else
... // tall (not blue) (not hairy)
} else {
... remaining 4 conditions
}
You could also adapt your if/else to a switch/case (which I understand is faster)
pre-generating A,B,C,D and E as booleans rather than evaluating them in if conditions blocks would provide both readability and performance. If you're also concerned about performance the different cases, you may organise them as a tree or combine them into a single integer (X = (A?1:0)|(B?2:0)|...|(E?16:0)) that you'd use in a switch.
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. */
}