How does a statement like this execute?
int x = 2, y = 3;
if (x != 0) if (x < 10) if (y < 10) {
x++;
y++;
System.out.printf("X and Y are: %d, and %d", x, y);
}
How does a statement like this execute?
int x = 2, y = 3;
if (x != 0) if (x < 10) if (y < 10) {
x++;
y++;
System.out.printf("X and Y are: %d, and %d", x, y);
}
If it could be compiled, it would get executed exactly like this:
if (x != 0)
if (x < 10)
if (y < 1o) {
x++;
y++;
System.out.println(x, y);
}
However, it's not very readable. You could improve its readability by using logical operators or proper line breaks and indentation.
Like this:
int x = 2, y = 3;
if ((x != 0) && (x < 10) && (y < 10))
{
x++;
y++;
System.out.println(x, y);
}
It operates like a Nested if. Why dont you check all condtion in the first if using a conditional AND. This way you would not need others.
However its a good practice to have braces for each if. This way its more readable and less error prone when the code undergoes changes in the future
if () if() if() is just short hand what it is really doing is
if(x != 0){
if(x < 10){
if(y < 1o){
x++;
y++;
System.out.println(x, y);
}else{}
}else{}
}else{}
They're nested. Basically, the curly brace is optional for one line statement blocks. I assume y < 1o
should be y < 10
, also your println
looks suspicious.
if (x != 0) {
if (x < 10) {
if (y < 10) {
x++;
y++;
// System.out.println(x, y);
System.out.println(Integer.toString(x) + " " + y);
}
}
}
You could certainly combine those into a single if
(and even one line) with an and
like
if (x != 0 && x < 10 && y < 10) {
System.out.printf("%d %d%n", x++, y++);
}
this is similar to
if (x != 0) {
if (x < 10) {
if (y < 10) {
x++;
y++;
System.out.println(x, y);
}
}
}
in an alternate way you can write
if((x != 0) && (x < 10) && (y < 10)) {
x++;
y++;
System.out.println(x, y);
}
Just use the && operator
int x = 2, y = 3;
if (x != 0 && x < 10 && y < 10) {
x++;
y++;
System.out.println(x, y);
}
It operates like a nested if as said by Andy. Instead of using this write all the conditions in one if statement and use && operator.
Using Java Logical Operators will resolve your problem.
Click this link to learn more
http://www.cafeaulait.org/course/week2/45.html