我正在尝试找到一种方法向用户询问是/否问题,以验证输入仅为是 (y/Y) 或否 (n/N)。我试图减少变量,同时仍然保持可读性。到目前为止,这是我想出的:
import java.util.Scanner;
public class InputValidation
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String answer;
do
{
System.out.print("Do you wish to proceed? (Y/N): ");
answer = input.next().trim().toUpperCase();
yesAnswer = answer.equals("Y");
} while (answer.matches("[YN]"));
if (yesAnswer)
{
// Do something
}
else
{
// Do something else
}
}
}
我不一定要寻找最少的字符数;更多的是简短而灵活的东西。有什么想法吗?
最佳答案
例如,根据您想要实现的目标,我可能会简单地直接评估输入,然后再确定实际结果
do {
System.out.print("Do you wish to proceed? (Y/N): ");
answer = input.next().trim().toUpperCase();
} while (!answer.matches("[YN]"));
boolean yesAnswer = answer.equalsIgnoreCase("Y");
这基本上会等到answer
匹配Y
、N
、y
、n
在确定 yesAnswer
之前。我可能做的下一件事是将其包装在方法中......
if (askYesNo("Do you wish to proceed? (Y/N): ")) {...
然后您可以继续为该方法提供可选的退出条件。
askYesNo("Delete all files [Ok/Cancel]", "(ok)?", "(cancel)?")
例如...
public class YesNo {
public static void main(String[] args) {
if (askYesNo("Do you wish to proceed? (Y/N): ")) {
System.out.println("Okay...");
}
if (askYesNo("Delete all Files? (Okay/Cancel): ", "okay", "cancel")) {
System.out.println("Make it so");
}
}
public static boolean askYesNo(String question) {
return askYesNo(question, "[Y]", "[N]");
}
public static boolean askYesNo(String question, String positive, String negative) {
Scanner input = new Scanner(System.in);
// Convert everything to upper case for simplicity...
positive = postive.toUpperCase();
negative = negative.toUpperCase();
String answer;
do {
System.out.print(question);
answer = input.next().trim().toUpperCase();
} while (!answer.matches(positive) && !answer.matches(negative));
// Assess if we match a positive response
return answer.matches(positive);
}
}
关于java - Java 请求确认的简短方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22523770/