[英]while loop in if statement in java
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");
}
}
您將x聲明為30,if循環執行if(x<20)
,該值始終為false,因此它無需執行else
語句即可立即執行else
語句。 您要么聲明x
小於20,要么更改if語句。
您的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
您為x分配的值是30,但是在您的條件下要檢查x小於20,因此條件將失敗並且將無法執行...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.