我有一个确认用户输入正确的验证类。此类中的一个方法尝试验证继续应用程序关键字。用户可以输入y或Y继续,n或N退出。任何其他字母都应该通过警告消息回答,然后是用户输入其答案的另一个机会。这是我为该方法编写的代码。
public static String getValidContinueCode(Scanner sc, String prompt)
{
String choice = "";
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.next().equalsIgnoreCase("y"))
{
choice = sc.next();
isValid = true;
}
else if (sc.next().equalsIgnoreCase("n"))
{
choice = sc.next();
isValid = true;
}
else
{
System.out.println("Please enter y or n");
}
}
return choice;
}
答案 0 :(得分:1)
当您从具有sc.next()
的扫描仪中读取该字符时,您无法再次阅读该字符。您需要在阅读时存储它并围绕读取值构建逻辑。
public static String getValidContinueCode(Scanner sc, String prompt) {
String choice = "";
boolean isValid = false;
while (!isValid) {
System.out.print(prompt);
choice = sc.next();
if (choice.equalsIgnoreCase("y")) {
isValid = true;
}
else if (choice.equalsIgnoreCase("n")) {
isValid = true;
}
else {
System.out.println("Please enter y or n");
}
}
return choice;
}
您可以做几项小改进。你可能只想返回一个带答案的布尔值。像这样。
public static boolean getValidContinueCode(Scanner sc, String prompt) {
while (true) {
System.out.print(prompt);
if (sc.next().equalsIgnoreCase("y")) {
return true;
}
else if (sc.next().equalsIgnoreCase("n")) {
return false;
}
else {
System.out.println("Please enter y or n");
}
}
}
答案 1 :(得分:0)
试试这个
public static void main(String[] args) {
getValidContinueCode(new Scanner(System.in),"");
}
public static void getValidContinueCode(Scanner sc,String code) {
code = "enter a letter";
boolean status = true;
while (status) {
System.out.println(code);
String check = sc.next();
if (check.equalsIgnoreCase("y")) {
sc = new Scanner(System.in);
code = "ok";
status = true;
} else if (check.equalsIgnoreCase("n")) {
sc = new Scanner(System.in);
code = "exit";
System.out.println("exit");
status = false;
} else {
code = "retry";
status = true;
}
}
}