naeem
naeem

Reputation: 43

while loop in if statement in java

while loop is not working in the if statement, why its not working... and how can while loop can work in if curly braces.

public static void main(String[] args) {
    int x = 30;

    if (x < 20) {
        System.out.print("This is if statement");         
        int a = 10;
        while(a < 20) {
            System.out.print("value of x : " + a );
            a++;
            System.out.print("\n");
        } 
    } else {
        System.out.print("This is else statement");
    }        
}

Upvotes: 0

Views: 101

Answers (3)

amk
amk

Reputation: 70

You declared x as 30, the if loop executes if(x<20) which is always false, so its performing the else statement immediately without going thru the if statement. You either have to declare x for something less than 20 or change the if statement.

Upvotes: 1

Shan
Shan

Reputation: 41

you assigned the value for x is 30 , but in your condition you are checking x is less than 20 , hence it the condition will fail and it wont execute...

Upvotes: 0

Kerem
Kerem

Reputation: 888

Your if statement doesn't meet the condition. Try this:

public static void main(String[] args) {
    // TODO code application logic here

    int x = 10;

    if( x < 20 ) {
    System.out.print("This is if statement");         
      int a = 10;
    while( a < 20 ) {
     System.out.print("value of x : " + a );
     a++;
     System.out.print("\n");
  }


  }else {
     System.out.print("This is else statement");
  }

}

And output:

This is if statementvalue of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Upvotes: 0

Related Questions