【问题标题】:while loop in if statement in javajava中if语句中的while循环
【发布时间】:2018-04-15 15:42:23
【问题描述】:

while 循环在 if 语句中不起作用,为什么它不起作用...以及 while 循环如何在 if 大括号中起作用。

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

【问题讨论】:

  • 因为30不小于20。
  • 感谢我的愚蠢

标签: java if-statement while-loop


【解决方案1】:

您将 x 声明为 30,if 循环执行 if(x&lt;20) 始终为 false,因此它立即执行 else 语句而不通过 if 语句。 您要么必须为小于 20 的值声明 x,要么更改 if 语句。

【讨论】:

    【解决方案2】:

    您的 if 语句不满足条件。试试这个:

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

    然后输出:

    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
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2016-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-19
        • 2013-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多