is there an equivalent if statement in java as this python one? - java

I usually code python, but decided to try to learn a new language (Java). I am a complete beginner with around 2 hours of experience. In python, we can use "or" so that if one condition is satisfied it executes the block of code.EG:
if x>y or 10<12:
print("one of these is true")
is there an equivalent for this in java ?

I quess
if( x > y || 10 < 12) {
System.out.println("one of these is true");
}
should do the thing.

This solution will work for you.
if (x>y || 10<12) {
print("one of these is true");
}

The equivalent if-statement would be
if (x > y || 10 < 12) {
....
}
Alternatively you can just skip that, since 10 < 12 will always evaluate to true.

Related

If statements with 3+ variable comparisons using && or alternate options

I'm attempting the below:
if(p1S > p2S && p3S)
}
But the IDE doesn't like the && here.
So, how would I compare these 3 ints to find the one with the highest value, thus moving forward.
Aka: If Int 1 is greater than int 2, and int 3, then do this. . .
I suspect I just don't know the syntax well enough just yet (I've only just started college for CS).
Is this what you want?
if(p1S > p2S && p1S > p3S)
}
The reason the previous code didn't work is that the first part
if(p1S > p2S && p3S)
}
evaluates to:
if(boolean && p3S)
}
And you can't do an && between a boolean and an int.

can you have two conditions in an if statement

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")) {
...
}

explain this line of code android

I am beginner to android, I am looking at this tutorial and came accross this code:
int temp = (sensor.getType() == Sensor.TYPE_ACCELEROMETER) ? 1 : 0;
can some one explain this for me.
May be this question is duplicate, but I don't know what to search for.
It will be great if you can tell me what it is in C# aswell.
(sensor.getType() == Sensor.TYPE_ACCELEROMETER) ? 1 : 0;
means
int result;
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER)
result = 1;
else
result = 0;
I am not 100% sure as what you want to be explained, but it seems that you are not understand/knowing about the ternary operator in Java.
It essentially means:
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
temp = 1;
}
else {
temp = 0;
}
Furthermore, I am unsure if this is correct Java code. It seems like you have left out something of your question, as the ternary operator most likely belongs to either an assignment or a return statement.
If you are talking about the parenthesis, question mark, and colon, then... it goes like so
(Condition ? If_condition_is_true_do_this : otherwise_do_this);
Exactly like doing this:
if(Condition)
If_condition_is_true_do_this
else
otherwise_do_this
And it is the same syntax in C#;
This is Java, not C# but ternary operators exist there as well.
About ternary operators, click here.
What the (full) code (not your snippet) does here is to check the sensor variable for equality with class constant Sensor.TYPE_ACCELEROMETER and assign the missing variable on the left with 1 if they are equal or 0 otherwise.

Ternary if operator inside a regular if one

In Java, if I use a ternary if operator inside a regular if, for example:
if ((x > y - z) ? true : callLongWaitedMethod(many, parameteres)) {
loveTeddyBear();
}
will it execute the callLongWaitedMethod if x > y - z is indeed true? I hope it is not and I can use this nice statement, slightly complicated at the first glance, but more attractive to compare with the extra boolean variable:
boolean b = (x > y - z) ? true : callLongWaitedMethod(many, parameteres);
if (b) {
loveTeddyBear();
}
especially if I'm using this inside a big loop which iterates over and over, so creating boolean each time will not be nice from the performance point of view while if I declare the boolean outside the loop, I may miss the neat because of the big size of the loop.
This will work as you hope, but it would be clearer to simply use the normal || operator to accomplish exactly the same result:
if ((x > y - z) || callLongWaitedMethod(many, parameteres)) {
loveTeddyBear();
}
According to the Java Language Specification 15.25, the long method will only be evaluated if necessary:
The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.
callLongWaitedMethod will not be called if x > y - z is true.
If you want to execute callLongWaitedMethod when (x > y - z) is true you actually have to swap the expression:
if ((x > y - z) ? callLongWaitedMethod(many, parameteres) : true ) {
loveTeddyBear();
}
It seems like you have the answer you want. You could also just use debugging statements with a simple version of your code to see what gets executed as a way of verifying the behavior. Something like
if ((1 > 2) ? true : someSimpleMethod()) {
System.out.println("true if");
}
And as your someSimpleMethod() have
public boolean someSimpleMethod() {
System.out.println("calling someSimpleMethod()");
return true;
}
From there you can swap 1 and 2 to see if the someSimpleMethod() would execute.
You should ask yourself as the coder, if you can't figure out what it's going to do, should you really be coding it that way? why not just this:
if ( (x>y-z) ||
(x<=y-z && callLongWaitedMethod(many, parameteres))) {
loveTeddyBear();
}
This will make much more sense to the novice programmer who is not familiar with your code.

Why does "do while" require a semicolon at the end? (C/C++/Java/etc) [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
In C/C++ why does the do while(expression); need a semi colon?
I understand the structure of a "do while" loop compared to a "while" loop. What I don't understand, is why does the language require this syntax:
do{
statements();
} while(condition);
Is it absolutely necessary for the language to have a semicolon at then end of this expression? Or is this more for ease of writing a compiler?
Since the } isn't the end, then it helps to have some way to know that the end of the statement is reached, hence the semi-colon.
It is possible to write a language without it, but it makes more sense to require it, in these languages.
At least in java, you can't write:
} while (i < 10) && (j != 8);
without getting such errormessages:
NodeSorter.java:24: ';' expected
} while (i < 10) && (j != 8);
^
NodeSorter.java:24: not a statement
} while (i < 10) && (j != 8);
^
NodeSorter.java:24: ';' expected
} while (i < 10) && (j != 8);
^
3 errors
So I guess it is for reasons of symetry - maybe it is more easy to write a parser that way.

Categories

Resources