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.
Related
I have an if statement with many conditions (have to check for 10 or 15 constants to see if any of them are present.)
Instead of writing something like:
if (x == 12 || x == 16 || x == 19 || ...)
is there any way to format it like
if x is [12, 16, 19]?
Just wondering if there is an easier way to code this, any help appreciated.
The answers have been very helpful, but I was asked to add more detail by a few people, so I will do that to satiate their curiosity. I was making a date validation class that needed to make sure days were not > 30 in the months that have only 30 days (of which there are 4, I think) and I was writing an if statement to check things like this:
if (day > 30 && (month == 4 || month == 6 || month == 9 || month == 11))
I was just wondering if there was a faster way to code things like that - many of the answers below have helped.
I use this kind of pattern often. It's very compact:
// Define a constant in your class. Use a HashSet for performance
private static final Set<Integer> values = new HashSet<Integer>(Arrays.asList(12, 16, 19));
// In your method:
if (values.contains(x)) {
...
}
A HashSet is used here to give good look-up performance - even very large hash sets are able to execute contains() extremely quickly.
If performance is not important, you can code the gist of it into one line:
if (Arrays.asList(12, 16, 19).contains(x))
but know that it will create a new ArrayList every time it executes.
Do you want to switch to this??
switch(x) {
case 12:
case 16:
case 19:
//Do something
break;
default:
//Do nothing or something else..
break;
}
If the set of possibilities is "compact" (i.e. largest-value - smallest-value is, say, less than 200) you might consider a lookup table. This would be especially useful if you had a structure like
if (x == 12 || x == 16 || x == 19 || ...)
else if (x==34 || x == 55 || ...)
else if (...)
Set up an array with values identifying the branch to be taken (1, 2, 3 in the example above) and then your tests become
switch(dispatchTable[x])
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
}
Whether or not this is appropriate depends on the semantics of the problem.
If an array isn't appropriate, you could use a Map<Integer,Integer>, or if you just want to test membership for a single statement, a Set<Integer> would do. That's a lot of firepower for a simple if statement, however, so without more context it's kind of hard to guide you in the right direction.
Use a collection of some sort - this will make the code more readable and hide away all those constants. A simple way would be with a list:
// Declared with constants
private static List<Integer> myConstants = new ArrayList<Integer>(){{
add(12);
add(16);
add(19);
}};
// Wherever you are checking for presence of the constant
if(myConstants.contains(x)){
// ETC
}
As Bohemian points out the list of constants can be static so it's accessible in more than one place.
For anyone interested, the list in my example is using double brace initialization. Since I ran into it recently I've found it nice for writing quick & dirty list initializations.
You could look for the presence of a map key or see if it's in a set.
Depending on what you're actually doing, though, you might be trying to solve the problem wrong :)
No you cannot do that in Java. you can however write a method as follows:
boolean isContains(int i, int ... numbers) {
// code to check if i is one of the numbers
for (int n : numbers) {
if (i == n) return true;
}
return false;
}
With Java 8, you could use a primitive stream:
if (IntStream.of(12, 16, 19).anyMatch(i -> i == x))
but this may have a slight overhead (or not), depending on the number of comparisons.
Here is another answer based on a comment above, but simpler:
List numbers= Arrays.asList(1,2,3,4,5);
if(numbers.contains(x)){
//
}
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 have an if statement with many conditions (have to check for 10 or 15 constants to see if any of them are present.)
Instead of writing something like:
if (x == 12 || x == 16 || x == 19 || ...)
is there any way to format it like
if x is [12, 16, 19]?
Just wondering if there is an easier way to code this, any help appreciated.
The answers have been very helpful, but I was asked to add more detail by a few people, so I will do that to satiate their curiosity. I was making a date validation class that needed to make sure days were not > 30 in the months that have only 30 days (of which there are 4, I think) and I was writing an if statement to check things like this:
if (day > 30 && (month == 4 || month == 6 || month == 9 || month == 11))
I was just wondering if there was a faster way to code things like that - many of the answers below have helped.
I use this kind of pattern often. It's very compact:
Define a constant in your class:
private static final Set<Integer> VALUES = Set.of(12, 16, 19);
// Pre Java 9 use: VALUES = new HashSet<Integer>(Arrays.asList(12, 16, 19));
In your method:
if (VALUES.contains(x)) {
...
}
Set.of() returns a HashSet, which performs very well even for very large sets.
If performance is not important, you can code the gist of it into one line for less code footprint:
if (Set.of(12, 16, 19).contains(x))
but know that it will create a new Set every time it executes.
Do you want to switch to this??
switch(x) {
case 12:
case 16:
case 19:
//Do something
break;
default:
//Do nothing or something else..
break;
}
If the set of possibilities is "compact" (i.e. largest-value - smallest-value is, say, less than 200) you might consider a lookup table. This would be especially useful if you had a structure like
if (x == 12 || x == 16 || x == 19 || ...)
else if (x==34 || x == 55 || ...)
else if (...)
Set up an array with values identifying the branch to be taken (1, 2, 3 in the example above) and then your tests become
switch(dispatchTable[x])
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
}
Whether or not this is appropriate depends on the semantics of the problem.
If an array isn't appropriate, you could use a Map<Integer,Integer>, or if you just want to test membership for a single statement, a Set<Integer> would do. That's a lot of firepower for a simple if statement, however, so without more context it's kind of hard to guide you in the right direction.
Use a collection of some sort - this will make the code more readable and hide away all those constants. A simple way would be with a list:
// Declared with constants
private static List<Integer> myConstants = new ArrayList<Integer>(){{
add(12);
add(16);
add(19);
}};
// Wherever you are checking for presence of the constant
if(myConstants.contains(x)){
// ETC
}
As Bohemian points out the list of constants can be static so it's accessible in more than one place.
For anyone interested, the list in my example is using double brace initialization. Since I ran into it recently I've found it nice for writing quick & dirty list initializations.
You could look for the presence of a map key or see if it's in a set.
Depending on what you're actually doing, though, you might be trying to solve the problem wrong :)
No you cannot do that in Java. you can however write a method as follows:
boolean isContains(int i, int ... numbers) {
// code to check if i is one of the numbers
for (int n : numbers) {
if (i == n) return true;
}
return false;
}
With Java 8, you could use a primitive stream:
if (IntStream.of(12, 16, 19).anyMatch(i -> i == x))
but this may have a slight overhead (or not), depending on the number of comparisons.
Here is another answer based on a comment above, but simpler:
List numbers= Arrays.asList(1,2,3,4,5);
if(numbers.contains(x)){
//
}
If i have the following if statement
if ( (row != -1) && (array[row][col] != 10) ) {
....
}
Where row is an int value and array is an int[][] object.
My question is, if this will throw an exception if row = -1 as the array won't have a -1 field, so out of bounds exception? Or will it stop at the first part of the if, the (row!=-1) and because that is false, it will ignore the rest?
Or to be sure it doesn't throw exception, i should separate the above if statement into two?
(Pls, don't tell me to check this out for my self :) I'm asking here 'cause i wanna ask a followup question as well ...)
It will stop safely before throwing an exception
The && is a short-circuiting boolean operator, which means that it will stop execution of the expression as soon as one part returns false (since this means that the entire expression must be false).
Note that it also guaranteed to evaluate the parts of the expression in order, so it is safe to use in situations such as these.
It will not throw an exception. However, if row is < -1 (-2 for example), then you're going to run into problems.
It will stop at the first part of the if. Java uses short circuite evaluation.
No, It wont. the compiler will not check the second expression if the first expression is false... That is why && is called "short circuit" operator...
Called a short-circuit evaluation via the && and if the row check fails, there is no point in continuing evaluation.
Most programming languages short-circuit the test when the first expression returns false for an AND test and true for an OR test. In your case, the AND test will be short-circuited and no exception will occur.
Many programming languages have short-circuit evaluation for logical operators.
In a statement such as A and B, the language will evaluate A first. If A is false, then the entire expression is false; it doesn't matter whether B is true or false.
In your case, when row is equal to -1, row != -1 will be false, and the short-circui the array expression won't be evaluated.
Also, your second question about the behavior of the array index is entirely language-dependent. In C, array[n] means *(array + n). In python, array[-1] gives you the last item in the array. In C++, you might have an array with an overloaded [] operator that accepts negative indexes as well. In Java, you'll get an ArrayIndexOutOfBoundsException.
Also, you might need something like the following (or just use a try/catch).
boolean isItSafe(int[][] a, int x, int y) {
boolean isSafe = true;
if (a == null || a.length == 0 || x >= a.length || x < 0 || y < 0 || y >= a[0].length ) {
isSafe = false;
}
return isSafe;
}
I have the following lines of code:
if(
checker.this()==false ||
checker.that()==false ||
checker.what()==true||
checker.cool()==false ||
checker.damm()==true
(...)
)
{
option = Option.FALSE;
}
With about 20 checks that must be performed. I've found this to be the most 'visual-tolerable' form of writing this if with multiple OR sequence but I'm not yet satisfied. Is there a coding standard for this?
Thanks.
The closest thing to a coding standard around this is Steve McConnel, whose authoritative book "Code Complete" recommends that complex conditions are factored into their own method, even if they are only used once. This allows for the name of the method to descibe what is happening.
if (checkValid(checker)) {...}
private boolean checkValid(Checker checker) {...}
checkValid is not a good name, of course, and should be replaced with something more descriptive. In this particular case you may want to make the check method part of "checker" object.
You should also avoid "something==true" and "something==false", and use "something" and "!something". This process is helped if you give the boolean methods appropriate names, like "isOpen()", "isEmpty()", rather than "open()" and "empty()". "checker.isOpen() && !checker.isEmpty()" is perfectly clear to read.
foo==false should better be written with !foo
Possibly, you can move this big if in a separate method: if (checker.complexConditionMet()) or if (complexConditionMet(checker)). It will improve readability.
checker.this()==false can be replaced by !checker.this()
I have never heard of a coding standard for anything like this. Personally, I would group several ifs into a method taking readability into consideration. For instance if you have something like:
if (this || that || what || where || why || cool || wow){ ... }
You could replace it with:
if (pronouns() || questions() || exclamations()){ ... }
I'd try to find common meaning between any of the various checks, and create functions from them.
When bundled together to describe a certain discrete, meaningful state of affairs or requirement, this can make the code less magical, easier to read, easier to test.
i.e. something like this, which is a bit "magical"
if (a == "world" || b == "dolly" || c == 42 || murder()) {
}
can be rendered more readable by changing it to something more like this:
if ( canSayHello() || canMeanLife()) {
}
...
boolean canSayHello() {
return a == "world" || b == "dolly"
}
boolean canMeanLife() {
return c == 42 || murder();
}