About if statement in Java lang - java

i want to ask,can i insert an if statement into an if statement
i have a code like this:
if(some codes && some codes || (if(some codes) && some codes))
//then something else..
is it possible.i tried it but it gives an error.maybe its a syntax error maybe this is not possible if you answer i will learn :)

That's a syntax error.
If you have multiple conditions that you want to test, e.g. a, b, c and d, then combining them with logical operators in a single if statement should be enough, e.g.:
if (a && b || (c && d))
{
...
}

Depending on what you mean by
some codes
and
then something else
you might do fine with an if... else if
if(some codes && some codes )
// ...
else if((some codes) && some codes)
// ...
If "some codes" means you're using the body of the if to execute statements I'd suggest refactoring to make the code more readable.

If you want a conditional value, you can use the ?: notation in boolean context as follows
if(cond1 && cond2 || cond3 ? cond4 : cond5){...}
meaning if cond3==true evaluates to if(cond1&&cond2||cond4), else if(cond1&&cond2||cond5)
example
int a=1;
int b=2;
int c=3;
int d=4;
if(a!=b && b!=c || a+b==c ? a+c==d : b+c==d){
System.out.println("yup");
}else{
System.out.println("nope");
}

Related

Is there a limit to how long an if statement can be in Java?

I was working on a game called the L game. In the function to check for a win, I had an if statement like this:
if (buttons[i][0].getText().equals(colour) || buttons[i][0].getText().equals("0") && buttons[i][1].getText().equals(colour) || buttons[i][1].getText().equals("0") && buttons[i][2].getText().equals(colour) || buttons[i][2].getText().equals("0") && buttons[i+1][2].getText().equals(colour) || buttons[i+1][2].getText().equals("0") && !(buttons[i][0].getText().equals(colour) && buttons[i][1].getText().equals(colour) && buttons[i][2].getText().equals(colour) && buttons[i+1][2].getText().equals(colour))) {
return false;
}
And this code didn't work. Not that I was getting an error, just it was not doing what it was supposed to do when a player won. However changed it to a few if statements in each other like this:
if (buttons[i][0].getText().equals(colour) || buttons[i][0].getText().equals("0")) {
if (buttons[i][1].getText().equals(colour) || buttons[i][1].getText().equals("0")) {
if (buttons[i][2].getText().equals(colour) || buttons[i][2].getText().equals("0")) {
if (buttons[i+1][2].getText().equals(colour) || buttons[i+1][2].getText().equals("0")) {
if (!(buttons[i][0].getText().equals(colour) && buttons[i][1].getText().equals(colour) && buttons[i][2].getText().equals(colour) && buttons[i+1][2].getText().equals(
return false;
}
}
}
}
}
And this does work.
Your two code snippets behave differently not because you have exceeded some "maximum characters in an if statement" limit, but because && has a higher precedence than ||.
When you say:
A || B && C || D
You meant
(A || B) && (C || D)
But without any parentheses, Java thought you meant:
A || (B && C) || D
This is because && has a higher precedence than ||. It's kind of like how you do multiplication first, than addition.
That aside, there is theoretically no limit on how long an if condition can be. It is not specified in the Java Language Specification. As long as you have enough RAM for the compiler, disk space to store the source file, and time for the compilation process, your code should compile eventually, if we assume the compiler implements the spec perfectly.
This doesn't mean that you should be writing super long if statements, though. Code is not only read by computers. Arguably, it is more often read by people than computers. So please keep that in mind when writing code.
A first step to refactoring your code would be to write a method like this:
private bool isButton0(int x, int y) {
return buttons[x][y].getText().equals("0");
}
so that you don't have to repeatedly say buttons[i][1].getText().equals("0").

Minifying Or/And expressions in Java?

I've always been curious if it's possible to simplify an Or expression Java. Example:
int mapVal = occurrenceMap.get(node.nextNode.nodeVal);
if (mapVal != null || mapVal != 5 )
versus...
if (occurrenceMap.get(node.nextNode.nodeVal) != ( null || 1) )
IMO, the second is more readable, but wondering if the language supports something like this.
Use getOrDefault
occurrenceMap.getOrDefault(node.nextNode.nodeVal, 5) != 5
if (occurrenceMap.get(node.nextNode.nodeVal) != ( null || 1) )
the second is more readable, but wondering if the language supports
something like this.
No Java not support that.
For a good solution I would like to use :
Integer i = occurrenceMap.get(node.nextNode.nodeVal);
if (i != null || i != 1)
Note : as Tim Biegeleisen mention in comment primitive int or type in general can't be null in Java.
First, int cannot be null. You don't need to check against null if you have an int. It just cannot happen.
Here is a method that checks whether a value is equal to any of a list of values:
public static <T> boolean anyEquals(T value, T... values) {
for (T val: values) {
if (val == value) { // or val.equals(value)
return true;
}
}
return false;
// implementation with streams
// return Arrays.stream(values).anyMatch(x -> x == value); // or x.equals(value)
}
Usage (supposing you are using Integers instead of int):
Integer i = ...;
boolean b = anyEquals(i, 5, 10, 15);
If you're into simplifying boolean expressions you should learn about some axioms and laws:
!!a = a
(!a || a) = true
(!a && a) = false
(true && a) = a
(false && a) = false
(true || a) = true
(false || a) = a
(!a || !b) = !(a && b)
(!a && !b) = !(a || b)
(a != b) = !(a == b)
(a <= b) = (b > a)
(a >= b) = (b < a)
The second one you've mentioned can't possibly be used in
Java because (a || b) already has a meaning so a == (c || d) already has a fixed meaning and changing this would probably break a lot of code. There might be languages that support such notations but they'll use a different operator instead of the binary boolean operator because otherwise it'd be impossible to distinguish what the programmer actually wants.
You could absolutely add such a feature to Java but you'd have to create a new operator to do this. But as of now: Java doesn't have this, and most languages don't.
Some languages allow you to do things like "a < b < c" which not all languages support (you'll have to write "a < b AND b < c").
You technically can create helper functions for this such as
"if isOneOf(mapVal, a, b)" but probably this is not going to be used widespread (most importantly because it'd require some runtime trickery to do this).

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

Java and and or operator not working

I am using the following statement to break out of the loop when two conditions met:
while (true)
{
if (uAnswer1.equals(answerB1) || uAnswer1.equals(answerB2)
|| uAnswer1.equals(answerB3)|| uAnswer1.equals(answerB4)
&&
uAnswer2.equals(answerS1)|| uAnswer2.equals(answerS2)){
break;
}
The loops breaks when one or both && conditions are met. However, I wrote the code to break the loop ONLY when both conditions are true.
Is there something missing from above statement?
Regards,
Shei7141.
wrap them in parentheses
if ( (uAnswer1.equals(answerB1) || uAnswer1.equals(answerB2)
|| uAnswer1.equals(answerB3)|| uAnswer1.equals(answerB4))
&&
(uAnswer2.equals(answerS1)|| uAnswer2.equals(answerS2)) )
or
even make a HashSet of correct answers and do this will be clean and will be efficient too
answers1Set.contains(uAnswer1) && answers2Set.contains(uAnswer2)
above code shows that uAnswer1.equals(answerB4) && uAnswer2.equals(answerS1) are in AND condition
while (true)
{
if ((uAnswer1.equals(answerB1) || uAnswer1.equals(answerB2)
|| uAnswer1.equals(answerB3)|| uAnswer1.equals(answerB4))
&&
(uAnswer2.equals(answerS1)|| uAnswer2.equals(answerS2))){
break;
}
while (true)
{
if ((uAnswer1.equals(answerB1) || uAnswer1.equals(answerB2)
|| uAnswer1.equals(answerB3)|| uAnswer1.equals(answerB4))
&&
(uAnswer2.equals(answerS1)|| uAnswer2.equals(answerS2)))
break;
}

check Equal and Not Equal conditons for double values

I am facing difficulty in comparing two double values using == and !=.
I have created 6 double variables and trying to compare in If condition.
double a,b,c,d,e,f;
if((a==b||c==d||e==f))
{
//My code here in case of true condition
}
else if ((a!=b||c!=d||e!=f))
{
//My code here in case false condition
}
Though my condition is a and b are equal control is going to else if part
So I have tried a.equals(b) for equal condition, Which is working fine for me.
My query here is how can I check a not equal b. I have searched the web but I found only to use != but somehow this is not working for me.
If you're using a double (the primitive type) then a and b must not be equal.
double a = 1.0;
double b = 1.0;
System.out.println(a == b);
If .equals() works you're probably using the object wrapper type Double. Also, the equivalent of != with .equals() is
!a.equals(b)
Edit
Also,
else if ((a!=b||c!=d||e!=f))
{
//My code here in case false condition
}
(Unless I'm missing something) should just be
else
{
//My code here in case false condition
}
if you really want invert your test conditions and test again,
else if (!(a==b||c==d||e==f))
Or use De Morgan's Laws
else if (a != b && c != d && e != f)
You can use
!a.equals(b) || !c.equals(d) || !e.equals(f)
Well with double data type you can use
==,!= (you should try to use these first.. )

Categories

Resources