[英]java user validation for string input until correct input is given
我将如何使用 while 循环不断要求用户重复输入有效答案,直到给出有效输入并在给出有效输入时结束程序? 我只知道如何使用int
和 numbers。 我对字母感到困惑。 我应该如何应用 NOT 运算符或其他逻辑运算符|| &&
|| &&
。
Scanner myScan = new Scanner(System.in);
System.out.println("Enter food");
String food = myScan.nextLine();
if (food.equalsIgnoreCase("b"))
{
System.out.println("beans");
}
else if (food.equalsIgnoreCase("e"))
{
System.out.println("eggs");
}
else
{
System.out.println("error");
}
一种方法是定义一个“标志”变量,然后循环直到它为“真”。 例如:
Scanner myScan = new Scanner(System.in);
boolean done = false;
while (!done) {
System.out.println("Enter food");
String food = myScan.nextLine().toLowerCase();
switch (food) {
case "b" :
System.out.println("beans");
done = true;
break;
case "e" :
System.out.println("eggs");
done = true;
break;
...
default :
System.out.println("error");
}
}
在一个非常简单的层面上,我会使用do-while
循环,因为您想至少进入循环一次。 然后我会使用boolean
标志来确定输入的有效性,并基于此做出进一步的决定,例如......
Scanner myScan = new Scanner(System.in);
boolean userInputCorrect = false;
String food = null;
do {
System.out.println("Enter food");
food = myScan.nextLine();
userInputCorrect = food.equalsIgnoreCase("b") || food.equalsIgnoreCase("e") || food.equalsIgnoreCase("exit");
if (!userInputCorrect) {
System.out.println("Error");
}
} while (!userInputCorrect);
System.out.println("You selected " + food);
扩展的解决方案可能会使用某种valid
方法,我可以将String
传递给该方法并让它根据已知值验证输入,但这可能有点超出了问题的范围
正如已正确指出的那样,但其他人指出,将输入转换为小写一次并比较所有值会更有效,在这种情况下,最好使用switch
语句......
Scanner myScan = new Scanner(System.in);
boolean userInputCorrect = false;
String food = null;
do {
System.out.println("Enter food");
food = myScan.nextLine();
switch (food.toLowerCase()) {
case "b":
case "e":
case "exit":
userInputCorrect = true;
break;
default:
System.out.println("Error");
}
} while (!userInputCorrect);
System.out.println("You selected " + food);
但你也可以这样做...
food = myScan.nextLine().toLowerCase();
userInputCorrect = food.equals("b") || food.equals("e") || food.equals("exit");
您也可以使用Map
,不用担心添加更多食物
Scanner myScan = new Scanner(System.in);
System.out.println("Enter food");
String food;
Map<String, String> foodMap = new HashMap<>();
foodMap.put("e", "Eggs");
foodMap.put("b", "Beans");
// add more food
while (true) {
food = myScan.nextLine();
String value = foodMap.get(food);
if (value == null) {
System.out.println("Error!");
break;
}
System.out.println(value);
}
首先是使用标志的坏习惯,你应该使用的是一种叫做Do while Loop 的东西。
do {
//block of code to be executed
} while(booleanExpression);
do while 循环将do
块中的代码,然后检查while
表达式。
对于您的情况,您可以执行以下操作:
Scanner myScan = new Scanner(System.in);
String food;
do{
System.out.println("Enter food");
food = (myScan.nextLine()).toLoweCase();
}while(!food.equals("b") || !food.equals("c"))
if (food.equals("b"))
{
System.out.println("beans");
}
else if (food.equals("e"))
{
System.out.println("eggs");
}
如果食物的数量继续增长,您可能会遇到问题,以备将来证明。 考虑使用数组或数组列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.