Java中if语句内的while循环未执行?原因及解决方法
问题分析与解决方案
嘿,我来帮你捋清楚这个问题!你的while循环没运行,根本原因不是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"); } }
你定义的x是30,而if的判断条件是x < 20——30明显大于20,所以这个条件不成立,程序直接跳过if块,执行else里的代码了。那if块里的while循环自然没机会跑起来。
怎么让while循环正常执行?
有两种简单的修改方式,选一种就行:
修改if的判断条件:把
x < 20改成符合x当前值的条件,比如x > 20,这样if块就能被触发了:public static void main(String[] args) { int x = 30; // 把条件改成x>20,匹配当前x的值 if (x > 20) { System.out.print("This is if statement\n"); 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"); } }修改x的初始值:把x改成小于20的数,比如15,这样原来的
x < 20条件就成立了:public static void main(String[] args) { // 把x改成15,满足x<20的条件 int x = 15; if (x < 20) { System.out.print("This is if statement\n"); 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"); } }
修改后运行代码,你就能看到while循环正常输出内容啦~
内容的提问来源于stack exchange,提问作者naeem
相关产品推荐
相关产品推荐

