我正试图找一种方法向用户询问是/否问题,该问题验证输入仅为是(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
}
}
}
我不一定要寻找最少量的角色;更多简短而灵活的东西。有什么想法吗?
答案 0 :(得分:2)
根据您想要实现的目标,我可能只是在确定实际结果之前直接评估输入,例如
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);
}
}