它編譯,只是它不會初始化while (choice = false)
因此無論輸入什麼ans
,它都不會顯示「Invalid input,enter a,b,c:」並重申。布爾方法不返回false
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;
}
}
}
我想你可能想'=='而不是'='。比較與分配。更好的是,你可以使用'while(choice)'這個檢查是否爲true或'while(!choice)'這個檢查是否爲false。 – csmckelvey 2014-11-25 03:27:47
我還注意到了一件事,但它不是問題的原因。你有三個choice.equalsIgnoreCase(「a」)..只是爲了引起你的注意。 – 2014-11-25 03:48:49