Reputation:
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);
}
Upvotes: 2
Views: 8598
Reputation: 1
Using Java Logical Operators will resolve your problem.
Click this link to learn more
http://www.cafeaulait.org/course/week2/45.html
Upvotes: 0
Reputation: 201409
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++);
}
Upvotes: 0
Reputation: 59
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.
Upvotes: 0
Reputation: 147
Just use the && operator
int x = 2, y = 3;
if (x != 0 && x < 10 && y < 10) {
x++;
y++;
System.out.println(x, y);
}
Upvotes: 0
Reputation: 2188
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);
}
Upvotes: 0
Reputation: 93
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{}
Upvotes: 0
Reputation: 2300
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
Upvotes: 0
Reputation: 86381
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.
Upvotes: 2
Reputation: 4638
Like this:
int x = 2, y = 3;
if ((x != 0) && (x < 10) && (y < 10))
{
x++;
y++;
System.out.println(x, y);
}
Upvotes: 1