Java difference between || and && in this example - java

I am making a counter between number ranges and not sure the correct way to do this. I have always used the || operator but reading some examples, I feel I should be using the && command. Here is my example problem...
if(value >= 1 || value <=10){
count1++;
}
else if(value >= 11 || value <= 20){
count2++;
// AND SO ON........
Or should I be using the && operator like
if(value >= 1 && value <= 10){
count1++;
}
else if value >= 11 && value <= 20){
count2++;
}

|| means "or".
&& means "and".
value >= 1 || value <= 10 makes no sense because it's always true. All numbers are 1 or more, or 10 or less. Some numbers are both, but that doesn't matter.
value >= 1 && value <= 10 makes far more sense. There's a limited range of numbers ([1..10]) for which both the first condition and the second condition are true.

|| is the or operator, so the condition value >= 1 || value <=10 is true for all values if you think about it. So, unless you want your counts to be meaningless, use && which is the and operator.

Related

Condition for while loop doesn't work in java

I want the loop to repeat if the number is not equal to 0 and rest%2 is equal to 1 or -1. But this does not seem to work:
while (number != 0 && rest%2 == 1 || rest%2 == -1)
How do I have to write the code so it works?
While it's good to learn about operator precedence, your expression can be reduced:
while (number != 0 && rest%2 != 0)
Put another way, n % 2 is 0 for positive and negative even numbers and something not even must be odd (which is what you are testing).
This is the correct way:
while (number != 0 && (rest%2 == 1 || rest%2 == -1))
Have a look at Java operator precedence here https://introcs.cs.princeton.edu/java/11precedence/
If I understand correctly you want to enter the loop in two cases:
number != 0 && rest%2 == 1
OR
rest%2 == -1
If that's true consider using parentheses:
while ((number != 0 && rest%2 == 1) || rest%2 == -1)

Does a simpler representation of this if condition exist?

I used the below conditional statement to ensure that the city name given is of valid length. Length of city should be greater than or equal to 3 and less than or equal to 20.
if(city.length()<3 || city.length()>20) return false;
else return true;
I am told that this conditional statement can be further simplified. Is that right? Then what is the simplified code?
return !(city.length() < 3 || city.length() > 20)
or
return city.length() >= 3 && city.length() <= 20
I simplified your code from IntelliJ IDEA IDE.
Actually it itself suggested to simplify when I used your code there. I recommend you to try IntelliJ IDEA.
return city.length() >= 3 && city.length() <= 20;
If you are already using the IDE, just move the cursor to the code with warning and press ALT+Enter and simplify it.
If city.length() is cheap, then write
return city.length() >= 3 && city.length() <= 20
else you ought to pre-compute city.length() to avoid the potential for two evaluations:
const auto&& /*assuming C++, for Java, you need to use the specific type*/ l = city.length();
return l >= 3 && l <= 20;

How to check string length range in a short form in java?

How to check string range in a short from in java?
if( !(str2.length() >= 3) && !(str2.length() <= 15)){
System.out.println("Minumum length required");
}
rather than using like above. is there any short??
(!(str2.length() >= 3) && !(str2.length() <= 15))
is the same as
( (str2.length() < 3) && (str2.length() > 15))
is the same as
(str2.length() < 3) && (15 < str2.length())
which is always false.
There is no number that is both less than 3 and greater than 15.
So these are pointless comparisons.
If you want to know that length is between 3 and 15, inclusive, use
if (3 <= str2.length() && str2.length() <= 15)
It's easy on the eyes and reminds people of familiar math expressions like 3 ≤ x ≤ 15.
But if that's what you meant your message needs fixing as well. If you meant what you said then the shortest version of this code is a blank line. It'll do the same thing.
This is not shorter but at least correct
if (!(str2.length() >= 3 && str2.length() <= 15)){
System.out.println("text length is not within range");
}
You can use a local variable.
int len = str2.length();
if (len < 3 || len > 15)
throw new IllegalArgumentException("String length" + len + " out of range.");
You could use a single comparison but this is not shorter.
if (len + Integer.MIN_VALUE - 3 > Integer.MIN_VALUE - 3 + 15)
This works as values below 3 will underflow and appear to be very large.

Java: making int and boolean comparable in "if" statements

Is it possible to have a statement such as...
if(delco == 1 && heavy < 5)
System.out.println("The total cost of your delivery is: $" + OPT_ONE);
if(delco == 1 && heavy >= 5 && heavy <= 20)
System.out.println("The total cost of your delivery is: $" + OPT_TWO);
...that also applies boolean logic to express an output? Something like this...
boolean overnight;
if(delco == 1 && heavy < 5) && (overnightShip == YES)
System.out.println("The total cost of your delivery is: $" + OPT_ONE + OVERNIGHT);
if(delco == 1 && heavy >= 5 && heavy <= 20) && (overnightShip == NO)
System.out.println("The total cost of your delivery is: $" + OPT_TWO);
I have tried a few variations of this code and the error I'm receiving states that they are incomparable types. How do I go about making them comparable?
You just missed some parentheses, because your logic seems OK. It should be, e.g.:
if ( (delco == 1 && heavy < 5) && (overnightShip == YES) )
...
Note the outer parentheses.
Also that assumes that you've defined YES to be a boolean constant equal to true, and that is redundant, so:
if ( (delco == 1 && heavy < 5) && (overnightShip) )
...
And in this case, those parentheses are redundant as well, and the whole thing simplifies to:
if ( delco == 1 && heavy < 5 && overnightShip )
...
Just use the boolean on its own:
if (delco == 1 && heavy < 5 && overnightShip)
Comparing a boolean "flag" variable with a boolean constant is poor style - always prefer testing the boolean as-is.
Boolean types in Java have the values:
true
false
Not:
YES
NO
unless you have defined these constants yourself somewhere
So your code should look like:
(overnightShip == true)
(overnightShip == false)
or even:
(overnightShip) // true
(! overnightShip) // false

What am i missing in this java code?

if (array[i]<(char)65 || array[i]>(char)122 &&
array[i]>(char)91 || array[i]<=(char)96)
System.out.println("False")
in this code, when i try to assign character 'C' (which is 67 btw) to array[i] it still says false. I did the math and it's not supposed to print "false" as I stated below this line.
(67 < 65 = 0 || 67 > 122 = 0) = 0
(67 > 91 = 0 || 67 <= 96 = 1) = 1
So, this leaves us: 0 & 1 = 0 .
Any ideas?
With some formatting, your code is:
if ( array[i] < (char)65 || array[i] > (char)122 &&
array[i] > (char)91 || array[i] <= (char)96 )
System.out.println("False");
Since && has higher precedence than || (see Operators), this is equivalent to:
if ( array[i] < (char)65
|| ( array[i] > (char)122 && array[i] > (char)91 )
|| array[i] <= (char)96 )
System.out.println("False");
which, since && is short circuiting, is behaviorally equivalent to:
if ( array[i] < (char)65
|| array[i] > (char)122
|| array[i] <= (char)96 )
System.out.println("False");
which, since the last case covers the first, is logically equivalent to:
if ( array[i] > (char)122 || array[i] <= (char)96 )
System.out.println("False");
You'll print False whenever the value it greater than 122 or less than or equal to 96. 67 is less than 96, so you print False. As pointed out the in comments, there is a precedence to the operators. Rather than learning all the details (to predict cases like this), it's easier just to use enough parentheses.
The && is evaluated first, and then the || according to the Java Operator Precedence. So it gets evaluated the following way for 'C'
67>122 && 67>91 //false
67<65 || false //false
false || 67<=96 //true
if you uses parentheses it will solve this problem
if ((array[i]<(char)65 || array[i]>(char)122) &&
(array[i]>(char)91 || array[i]<=(char)96))
I think you may try this by using brackets ():
if ((array[i]<(char)65 || array[i]>(char)122) && (array[i]>(char)91 || array[i]<=(char)96))
System.out.println("False")
Also to note that && has higher precedence

Categories

Resources