![](/img/trans.png)
[英]Catching and rethrowing an exception from a boolean method does return false whereas not doing anything causes the method not to return
[英]Boolean Method does not return false
它會編譯,只是不初始化while (choice = false)
所以無論輸入ans
,它都不會顯示“輸入無效,請輸入a,b,c:”並重復。
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
String ans;
boolean choice;
System.out.print("Enter a, b, c: ");
ans = kb.nextLine();
choice = isValidChoice(ans);
while (choice = false)
{
System.out.print("Invalid input, enter a, b, c: ");
ans = kb.nextLine();
choice = isValidChoice(ans);
}
if (choice = true)
{
System.out.println("Your input was " + ans);
}
}
public static boolean isValidChoice(String choice)
{
if (choice.equalsIgnoreCase("a") || choice.equalsIgnoreCase("a")
|| choice.equalsIgnoreCase("a"))
{
return true;
}
else
{
return false;
}
}
}
在需要比較時始終使用==
,這表示Java中的相等性,而=
表示賦值。 這與某些語言(例如PL / SQL)不同。
因此,當您調用while(choice =false)
,Java僅將false分配給變量choice,而不會將choice
與false進行比較。
您應該改用while(choice==false)
, if (choice == true)
在if (choice == true)
檢查操作員以獲取更多詳細信息
您正在使用要使用equals運算符的賦值。 while(!choice)
或while(choice==false)
。 if
相同。 在您的情況下,您需要區分有效選擇和實際選擇。 也許讓函數返回比布爾值更多的值更容易。
一個有用的提示:永遠不要忽略編譯器或IDE的警告。 它會告訴您是否做一些愚蠢的事情,例如在表達式中賦值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.