简体   繁体   English

在Java中的if语句中的while循环

[英]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. while循环在if语句中不起作用,为什么它不起作用...以及如果花括号则while循环如何工作。

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");
    }        
}

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. 您将x声明为30,if循环执行if(x<20) ,该值始终为false,因此它无需执行else语句即可立即执行else语句。 You either have to declare x for something less than 20 or change the if statement. 您要么声明x小于20,要么更改if语句。

Your if statement doesn't meet the condition. 您的if陈述式不符合条件。 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

您为x分配的值是30,但是在您的条件下要检查x小于20,因此条件将失败并且将无法执行...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM