[英]Is it possible to use a boolean expression in this manner?
我目前正在學習Java腳本並嘗試新事物,例如,我希望查看是否可以將布爾表達式設置為結束(如果該表達式檢測到從開始到結束的數字)。
或者換句話說,我想要的是3到8。我將明確說明我正在使用netbeans IDE。
在我的最后一個if語句中,我希望它結束詢問過程。 我希望它是一個簡單的修復程序,但是除非我創建了更多其他if語句,否則我想不出任何可以完成此操作的方法。
掃描儀輸入=新的Scanner(System.in);
int[][] table;
boolean stopasking = true;
while (stopasking = true){
System.out.println("Let's make a magic Square! How big should it be? ");
int size = input.nextInt();
if (size < 0)
{
System.out.println("That would violate the laws of mathematics!");
System.out.println("");
}
else if (size >= 9)
{
System.out.println("That's huge! Please enter a number less than 9.");
System.out.println("");
}
else if (size <= 2)
{
System.out.println("That would violate the laws of mathematics!");
System.out.println("");
}
else if (size == 3)
{
stopasking = false;
}
}
您使用了assignmnent運算符=
應該使用==
代替
當size<0
時條件size<=2
成立,因此if
兩個都可以使用一個
while(stopasking){
if (size <= 2) {
System.out.println("That would violate the laws of mathematics!\n");
} else if (size >= 9){
System.out.println("That's huge! Please enter a number less than 9.\n");
} else if (size == 3){
stopasking = false;
}
}
您可以通過這種方式使用布爾表達式作為退出循環的條件。 有人會說這是一個比break
更優雅的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.