what is the java syntax for saying
if x is not equal to a or b
I am trying to write an if else statement .. if a certain value is not equal to say 2 or 3 then do something else do something else :) thats confusing lol
Try this:
if (x != a && x != b) {
// Something (action x)
} else {
// Something else (action y)
}
Note that it's an "and" condition even though you're asking whether x is equal to a or b because each condition is negative. The other way you could represent this (if you find it more readable) is:
if (!(x == a || x == b)) {
// Something (action x)
} else {
// Something else (action y)
}
And at that point you may find it more readable still to get rid of the negation, but switch round what you do in the blocks:
if (x == a || x == b) {
// Action y
} else {
// Action x
}
These three blocks of code all do the same thing, but I think I'd find the bottom one the most readable as the condition is simple.
if ((x != a) && (x != b)) {
// do stuff
} else {
// do other stuff
}
if( x != a && x != b )
Notice it's an &&, not an ||
The condition ( x != 2 || x != 3 ) is always true: if x = 2, then x != 3 and the condition is true. if x = 1, then x != 2 and the condition is true.
What you're really saying is: if x is not one of 2 or 3, which is, x is not in the array [2,3], which is "x is not 2 neither 3", which is x != 2 and x != 3.
directly mimics the english sentence: if x is not equal to a or b
if (!(x == a || x == b))
{
doSomething();
}
else
{
somethingElse();
}
but if the extra not operator and parentheses hurts your eyes, use this(note the absence of the word Or in this condition, not anymore parallel with english sentence):
if (x != a && x != b)
{
doSomething();
}
else
{
somethingElse();
}
see my answer on programmer's ignorance pet peeve and Is it acceptable to only use the ‘else’ portion of an ‘if-else’ statement?, why i advocate constructing simple conditions(directly mimics english sentence, i.e. without sticky ANDs and too much NOTs)
if(x!=a && x!=b){
//do...
}
in java if-else is a control statement which is used to test condition and transfer the control based on the evolution of condition.
if((x!='a')||(x!='b'))//if a,b is char use quotes else avoid
{
//if expression is true
}
else
{
//if expression is false
}
if you want that code should be executed when x=a and x=b both then use '&&' instead of '||'.
For more details:
http://java.meritcampus.com/t/60/If-else-if-ladder?tc=mm70
Related
Suppose I have four variables x, y, z, w. I want to print:
"hello all non zero values" only if all x, y, z, w are non-negative and non-zero values.
If all the values are zero, then print "hello zero".
If any of the values (one, two or three but not all of them) is zero or negative then print "illegal values".
I've written a sample solution which handles and clubs negative as well as non-negative values:
if((x&y&z&w) == 0 && !(x==y && y==z && z==w && w==0)) {
System.out.println("illegal values");
} else {
System.out.println("hello all non zero values");
}
However, I am not able to handle the negative and positive values separately. Can anyone please suggest a solution for it?
The bit-fiddling approach:
String s;
int j = w & x & y & z;
int k = w | x | y | z;
if (k == 0)
s = "hello zero";
else if (j != 0 && k > 0)
s = "hello all non-zero values";
else
s = "illegal values";
System.out.println(s);
This works because the bitwise-and is zero if any of the four values is zero, the bitwise-or is non-zero if any of the four values is non-zero; and the sign bit is set in the result (i.e., negative) if the sign bit is set in any of the four values.
(And I use the temporary 's' because why write 3 calls to the same routine)
Edited: this answer was updated after a recent edit to the question, which has clarified the criteria.
It might help to reword your question in a different but equivalent way. You are basically printing "hello zero" if all of them are zero, "hello all non zero values" if all of them are positive, and "illegal values" in all other cases.
if (x == 0 && y == 0 && z == 0 && w == 0) {
System.out.println("hello zero");
} else if (x > 0 && y > 0 && z > 0 && w > 0) {
System.out.println("hello all non zero values");
} else {
System.out.println("illegal values");
}
Something like this?
if (x > 0 && y > 0 && z > 0 && w > 0) {
System.out.println("hello all non zero values");
} else if (x == 0 && y == 0 && z == 0 && w == 0) {
System.out.println("hello zero");
} else {
System.out.println("illegal values");
}
Does this work for you?
if ((x>0)&(y>0)&(z>0)&(w>0)) {
System.out.println("hello all non zero values");
} else {
System.out.println("illegal values");
}
Edit: this doesn't fully answer the question, my apologies
I have tried to do this in java however the && symbols keep on giving error.
Below is the code that I used:
int d = 18;
{
if ((d % 2) && (d% 3));
{
System.out.println("True!");
}
{
System.out.println("False!");
}
}
This is my code. I am not sure why its not working. Thanks
The error message is The operator && is undefined for the argument type(s) int, int. #
I have got it to work now. I have an else error . "The error says Syntax error on token "else", delete this token"
public class CS1702_Lab3_4 {
int d = 18;
{
if ((d % 2 == 0) && (d % 3 == 0));
{
System.out.println("True!");
}
else
{
System.out.println("False");
}
}
}
Also when I add an else it says Syntax error on token "else", delete this token
Please learn about the modulus operator, and how to check divisibility in java.
if ((d % 2 == 0) && (d % 3 == 0))
{
System.out.println("True!");
}
Also, you had a rogue semi-colon at the end of your if statement.
EDIT: Fixed code
public class CS1702_Lab3_4 {
public static void main(String[] args) { // Entry into our program
int d = 18;
if ((d % 2 == 0) && (d % 3 == 0)) {
System.out.println("Divisible!");
} else {
System.out.println("Not divisible!");
}
}
}
I'd recommend looking at some basic Java tutorials, however the fixes I applied included:
Contained your code inside of a method, specifically the main method, which is the entry point to a runnable Java application. Java is not a procedural language, code outside of variable, method, class, package and import declarations need to be contained inside of a method
Fixed syntax on your if statement, removed rogue semi colon
if ((d % 2) && (d% 3)); you have a semicolon ; at the end,
remove it.
If d == 18, then ((d%2) && (d%3)) = (0 && 0) = 0 So in this
case, What java sees is: if(0){ // ... }
If I remember correctly, this is valid in C/C++, but not in Java. That is why you get error.
Anyways, to fix the problem, you can do this:
if (((d % 2) == 0) && ((d % 3) == 0)){
System.out.println("Divisible!");
} else {
System.out.println("Not divisible!");
}
if condition expects boolean. Mod operation would not return boolean, this is why compiler is intelligent and gives you this error.
if you try to run
if (1 && 2) // this will give you an error as well.
The expressions need to evaluate to a boolean (either true or false) in order to understand operators like && and ||
Moreover, you statement will not work since you are using ; at the end.
When evaluating a Boolean expression in java, I find myself a bit bewildered by short circuit evaluation and pre-fix increment operators. Consider the following:
int e=20;
int f=25;
if(++e>21 || ++e>21 && f>30){
System.out.println("Hi");
}
System.out.println(e);
I understand that if ++e were greater than 21, the rest of the IF statement would skip over (due to short circuit eval). But in this case, it doesn't, as the first part is not true, so we move on to the AND statement. At this point, is e still 20? Or during the short circuit eval, did it go up to 21?
Well, I am assuming at this point, we evaluate the AND statement (as we normally do before OR), we add 1 to e, which I assume becomes 21 now? It is false, and therefore the entire AND statement is false.
Do we, at this point, go BACK and do the OR statement? Since it comes after AND? Shouldn't e be pumped up to 22 now? And since it's an OR statement, it should come out to TRUE OR FALSE, which should be TRUE, and "Hi" should appear on the screen. But it doesn't.
Weirdly, the value for e is 22 when the code finishes. 22 is the value we needed for the IF statement to be true, but the condition inside didn't run.
I am extremely confused.
Let's unwind what short-circuiting actually is!
int e=20;
int f=25;
if((++e>21) || (++e>21 && f>30)){
System.out.println("Hi");
}
System.out.println(e);
So, if that left hand side of the or condition evaluates to true, we don't need to do anything more, so let's be more explicit about that:
int e=20;
int f=25;
if (++e > 21)
{
System.out.println("Hi");
}
// the or becomes an else if, if the first condition fails then we check the second
else if (++e>21 && f>30)
{
System.out.println("Hi");
}
System.out.println(e);
Now, let's be more explicit about when that first increment happens:
int e=20;
int f=25;
e += 1;
if (e > 21) // e = 21, 21 is not > 21
{
System.out.println("Hi");
}
// We need to test this condition, as you've said
// e is still 21
else if (++e>21 && f>30)
{
System.out.println("Hi");
}
System.out.println(e);
Again, let's unwind what and means in terms of short-circuiting
int e=20;
int f=25;
e += 1;
if (e > 21) // e = 21, 21 is not > 21
{
System.out.println("Hi");
}
// We need to test this condition, as you've said
// e is still 21
else if (++e > 21) // the and becomes a nested if, first the left must be true before we test the right
{
if (f > 30)
{
System.out.println("Hi");
}
}
System.out.println(e);
And again, let's be explicit about that increment!
int e=20;
int f=25;
e += 1;
if (e > 21) // e = 21, 21 is not > 21
{
System.out.println("Hi");
}
// We need to test this condition, as you've said
// e is still 21
else
{
e += 1;
if (e > 21) // e is now 22, this condition succeeds
{
if (f > 30) // f is not >30, this condition fails!
{
System.out.println("Hi");
}
}
// e is still 22
}
// e is still 22
System.out.println(e);
Hopefully this makes it all clear!
EDIT: Actually, having re-read your question a couple of times, it appears you are getting confused with the precedence of the logical operators. You seem to think that the and should execute before the or right? presumably because and has the higher precedence. All that means, however, is that the implicit brackets go round the and first like so;
p || q && r == p || (q && r)
You should be able to see that in this form, the outside or must be evaluated first, before the and is. We always evaluate left to right!
Convert the following without if/loops. You can still use recursion, &&, || etc...
public boolean mystery(int n){
if(n == 0){
return false;
}
if(n%10 == 7){
return true;
}
return mystery(n/10)
}
I would like hints.
But I've been experimenting around.
We know that true && false == false and only true && true == true
So we must have that
return (n%10 == 7) && ....
Then for the second part, we could either get true or false, and if the second part is true, then our first part being true will result in everything being true, so I am thinking.
return (n%10 == 7) && ...
But I am thinking an issue might be that if n%10 isnt 7 right off that bat everything is false.
In my view, the ternary operator is still pretty much an 'if' statement - but that becomes a semantic debate. You can avoid using it entirely.
return (n % 10 == 7) || (n != 0 && mystery(n/10));
There are many ways: but to give you a start:
if(n == 0){
return false;
}
if(n%10 == 7){
return true;
}
return mystery(n/10)
}
is equivalent to
return n==0 ? false : n%10==7 ? true : mystery(n/10);
is equivalent to
return n!=0 ? n%10==7 ? true : mystery(n/10): false;
is equivalent to
return n!=0 && n%10!=7 ? mystery(n/10) : n!=0;
Was an interesting activity to solve. Solution below with proof of testing till 10k. mystery2 is the method of interest for you.
How I got the solution:
Started printing the results from 0 to 100 and identify the pattern - found the ones starting or ending with 7 would return true and all others false. The first if block which compares with zero is actually encountered by all the numbers which do not qualify reminder 7 rule in any position. Thus, reminder 7 is the only condition to get true result and everything else would enter recursion until it becomes 0 after the unit's position is complete. Equating to 0 is required as we should have a condition that ends the recursion (or ends in StackOverflowException).
public static void main(String[] args) {
for(int i = 0 ; i<=10000; i++){
if(mystery(i) != mystery2(i)){
System.out.println("Mismatch... "+i);
}
}
}
static boolean mystery(int n) {
if (n == 0) {
return false;
}
if (n % 10 == 7) {
return true;
}
return mystery(n / 10);
}
static boolean mystery2(int n) {
return n % 10 == 7 || (n != 0 && mystery2(n / 10));
}
here is what i tried. it says second operand is boolean whereas first is long. so & operator is undefined for long and boolean .
public static void powerOfTwo(long a){
if(a & (a-1) == 0 )
System.out.println("it's a power of two");
else
System.out.println("NOT a power of two");
}
You have to wrap the expression in extra parenthesis:
public static void powerOfTwo(long a) {
if ((a & (a - 1)) == 0)
System.out.println("it's a power of two");
else
System.out.println("NOT a power of two");
}
That's because the operator == takes precedence over & (see here), so without the braces, you have
a & (a - 1) == 0
which is the same as
a & ((a - 1) == 0)
and then the compiler complains about comparing a long (a) with a boolean (a-1 == 0)
You can use
return a != 0 && ((a & (a-1)) == 0);
however this is obscure. A simpler way is
return Long.bitCount(a) == 1
This is not entirely obvious either but having exactly one bit set means it must be a power of 2.