simple boolean question - java

What am I doing wrong here?
I am wanting to display integers from 1-100 who are divisible by either 6 or 7. That's done and working. The next step is to not display any that are divisible by both...that isn't working in my loop (those integers are still displaying)
for (int i = 1; i < 100; i++)
if (i % 6 == 0 || i % 7 == 0 && i % (6 * 7) != 0){
println(i);
}
Thanks!
Joel

try making your condition more explicit by adding (...), like so:
if (((i % 6 == 0 || i % 7 == 0) && (i % (6 * 7) != 0)) {
}
by default && takes precedence over ||

Missing parentheses:
for (int i = 1; i < 100; i++) {
if ((i % 6 == 0 || i % 7 == 0) && i % (6 * 7) != 0) {
println(i);
}
}

You could also use the exclusive or
for (int i = 1; i < 100; i++) {
if ((i % 6 == 0) ^ (i % 7 == 0)) {
println(i);
}
}
or just an unequal if ((i % 6 == 0) != (i % 7 == 0))
Since exclusive or is not used that often, I doubt this will increase the readability of the code...

I would simply stop worrying about how to evaluate precedence, and use something like:
for (int i = 1; i <= 100; i++) {
if ((i % 42) == 0) continue;
if ((i % 6) == 0) println (i);
if ((i % 7) == 0) println (i);
}
I'm assuming here that 1-100 was an inclusive range in which case you should use <= rather than <. It won't matter for your specific case since 100 is divisible by neither 6 nor 7.
Guess what? Any decent optimising compiler (including JIT ones) will probably end up generating the same code as for all the other possibilities. And, even if it didn't, it wouldn't matter unless you were calling this function a great many times.
I think that's a tiny bit more readable than:
if (i % 6 == 0 || i % 7 == 0 && i % (6 * 7) != 0) ...
or, worse yet, the Lisp-like thing you'll have to turn it into to get it working properly :-)
Keep in mind one possibility - you can change your loop to make it more efficient (sevenfold), for the specific case with 6 and 7, thus:
for (int i = 7; i <= 100; i += 7)
if ((i % 6) != 0)
println (i);
This uses the for loop itself to only check multiples of 7 and print them if they're not also multiples of 6.

for (int i = 1; i < 100; i++)
if ((i % 6 == 0 || i % 7 == 0) && !(i % 6 == 0 && i % 7 == 0)){
println(i);
}

Related

get characters from string by index in java

I may just be tired and not thinking properly anymore, but why is "13" only printed once here? (intelliJ tells me that "i == 11 | i == 13" is always true but I don't see how that makes sense)
for (int i = 0; i < 14; i++) {
System.out.println(i);
String line = clientReader.readLine();
int length = line.length();
if (i == 0 || i == 5 || i == 6) {
line = line.substring(7, length - 6);
} else if (i == 1 || i == 2 || i == 3 || i == 4 || i == 8 || i == 9 || i == 10 || i == 12) {
line = line.substring(8, length - 7);
} else if (i == 7) {
line = line.substring(9, length - 8);
} else if (i == 11 || i == 13) {
line = line.substring(10, length - 9);
}
data[i] = line;
System.out.println(i);
}
p.s. The line.substring does not give an error, if I add System.out.println(line) at the end of the last else if it prints the correct thing.
The last else if is always true because your loop control variable runs from 0 until 13 and the only two numbers you haven't checked before the last else if is 11 and 13 therefore if none of the above conditions are true then i will either be 11 or 13 hence why IntelliJ is smart enough to know it's always true and hence control will always be bound inside the last else if block when the above conditions are not met.
If you increase the loop condition to something like i < 15 or above then IntelliJ wouldn't state else if (i == 11 || i == 13) is always true as i could be 14.

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.

Simplify multiple similar statements on (while)

For example let's say i have this:
while( i1 % 1!=0 || i1 % 2!=0 || i1 % 11!=0 || i1 % 16!=0 ||
i1 % 7!=0 ||i1 % 3!=0 ||i1 % 12!=0 ||i1 % 17!=0 ||
i1 % 8!=0 ||i1 % 4!=0 ||i1 % 13!=0 ||i1 % 18!=0 ||
i1 % 9!=0 ||i1 % 5!=0 ||i1 % 14!=0 ||i1 % 19!=0 ||
i1 % 10!=0 ||i1 % 6!=0 ||i1 % 15!=0 ||i1 % 20!=0 ) {}
How can i simplify that?
Like while the module of i1 for 1-20 is different to 0. without all that mess.
Pardon if its a dumb question, I'm fairly new to this.
You can create a method that will generate the statement for you, and using a forloop to iterate 20 numbers and check if the modulo of each number is not equal to zero.
sample:
public boolean checkModulos(int toCheck)
{
for(int i = 0; i < 20; i++)
{
if(toCheck % i != 0)
return true;
}
return false;
}
to use it is:
while(checkModulos(i1))
You can work with the statement a bit. With DeMorgan's Law (!A || !B == !(A &&B)), you can turn it into !(i1 % 1 == 0 && i1 % 2 == 0 ... && i1 % 20 == 0)
Now think about the statement a bit. A number mod another equaling zero means the first number is divisible by the second. That means the statement really reads: not (i1 is divisible by all the numbers 1-20). So find a number n that is divisible by all the numbers 1-20, and have the loop become while( !(i1 % n == 0) ), or just while(i1 % n != 0)

How does Java evaluate this statement?

I have this expression in the if else statement
if (row % 2 == 0 && col % 2 == 0 || row % 2 == 1 && col % 2 == 1) {
return 0;
}
else {
return 1;
}
which behaves as intended, returning 0 when the row and column are either both even or both odd. What perplexes me is how Java didn't read it as
(row % 2 == 0 && (col % 2 == 0 || row % 2 == 1 && col % 2 == 1))
How exactly does Java evaluate a statement without parenthesis?
How exactly does Java read a statement without parenthesis?
By applying the operator precedence rules. The Java language specification says that && has a higher precedence than ||, and that means that:
row % 2 == 0 && col % 2 == 0 || row % 2 == 1 && col % 2 == 1
is equivalent to:
(row % 2 == 0 && col % 2 == 0) || (row % 2 == 1 && col % 2 == 1)
And in fact, == has a higher precedence than &&, so that is equivalent to:
((row % 2 == 0) && (col % 2 == 0)) || ((row % 2 == 1) && (col % 2 == 1))
This page from the Java Tutorial provides more information on operator precedence and how it affects expression evaluation.
For what it is worth, there is a natural parallel between operator precedence in a programming language and the meaning of simple arithmetical expressions ... as you were taught in primary school. For example, you were taught that 1 + 2 x 3 means the same thing as 1 + (2 x 3); i.e. the answer is 7 and not 9. In technical terms, the x (multiplication) operator has higher precedence than the + (addition) operator.
The idea is the same in a typical programming language, except that there is a larger range of operators to deal with ... and the rules are (generally speaking) more precisely specified1.
1 - For instance, since the evaluation of primaries and operators can in some cases have side effects, it can be important to know the precise order in which the sub expressions get evaluated.
That is because of the precedence order. && has precedence over ||.
Look here.

How to check if an integer can be divided by 3

How to check if my integer can be divided by 3 as below:
for(int i=0; i<24; i++){
//here, how to check if "i" can be divided by 3 completely(e.g. 3, 6, 15)?
}
Use the modulo operator.
if(i % 3 == 0)
Also see Modulo operation at Wikipedia
If you are using a loop, you can use the fact that every third number can be divided by 3.
for(int i = 0; i < 24; i += 3) {
System.out.println(i + " can be divided by 3");
System.out.println((i+1) + " cannot be divided by 3");
System.out.println((i+2) + " cannnot be divided by 3");
}
This avoids the need for a modulo and cuts the number of loops by a factor of 3.
Use the MOD operator
for(int i=0; i<24; i++){
if( i%3 == 0 )
// It is divisible by 3
}
Well, what you could do (it might be a bit faster; it is faster on my machine) is:
boolean canBeDevidedBy3 = ((int) (i * 0x55555556L >> 30) & 3) == 0;
instead of
boolean canBeDevidedBy3 = (i % 3) == 0;
However, the multiplication trick only works for -2 <= i <= 1610612735. This answer was inspired by this optimization question. But if I can give you a tip: use (i % 3) == 0. It's so much simpler, and will always work.
Check the remainder of i devided by 3
if (i % 3 == 0) {}
inside the loop:
if (i%3 == 0)
// it can be divided by 3
% is called "mod" or "modulus" and gives you the remainder when dividing two numbers.
These are all true:
6 % 3 == 0
7 % 3 == 1
7 % 4 == 3
if( i % 3 == 0 )
The % operator delivers you the rest of the division i / 3
if( i % 3 == 0 ){
System.out.println("can be divided by 3");
}else{
System.out.println("cant divide by 3");
}
Is this question for real?

Categories

Resources