2

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);
}
Nic
  • 12,220
  • 20
  • 77
  • 105

9 Answers9

2

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.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
1

Like this:

int x = 2, y = 3;
if ((x != 0) && (x < 10) && (y < 10))
{
    x++;
    y++;
    System.out.println(x, y);
}
Lawrence Aiello
  • 4,560
  • 5
  • 21
  • 35
0

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

Chiseled
  • 2,280
  • 8
  • 33
  • 59
0

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{}
Elton
  • 83
  • 7
  • not including braces just means the next statement is considered as the body of the if statement. This is bad practice because what they could have done instead is just if( case && case && case){//do stuff} – Elton Nov 04 '14 at 22:58
0

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++);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

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);
}
Johny
  • 2,128
  • 3
  • 20
  • 33
0

Just use the && operator

int x = 2, y = 3;
if (x != 0 && x < 10 && y < 10) {
    x++;
    y++;
    System.out.println(x, y);
}
Orangelight
  • 147
  • 2
  • 3
  • 8
0

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.

viggy22
  • 59
  • 3
0

Using Java Logical Operators will resolve your problem.
Click this link to learn more
http://www.cafeaulait.org/course/week2/45.html