我想让do循环在用户输入的字母不等于所需字母(a-i)的情况下运行。出于某种原因,即使我输入正确的字母,它也会永远循环。
我已经尝试在比较中使用切换用例以及!=。
这是我的代码:
do {
System.out.println("Please enter the location of your battleship, starting with the first letter value. Make sure it is from the letters a-i.");
lL1=in.nextLine();
if (!lL1.equals("a")||!lL1.equals("b")||!lL1.equals("c")||!lL1.equals("d")||!lL1.equals("e")||!lL1.equals("f")||!lL1.equals("g")||!lL1.equals("h")||!lL1.equals("i")){
System.out.println("Invalid Input. Try again.");
}//End if statement
}while(!lL1.equals("a") || !lL1.equals("b") || !lL1.equals("c") || !lL1.equals("d") || !lL1.equals("e") || !lL1.equals("f") || !lL1.equals("g") || !lL1.equals("h") || !lL1.equals("i"));
我在Java方面的技能是有限的,但这应该可以工作,除非我缺少明显的东西。任何帮助都将是惊人的!
最佳答案
您可能不希望为每种输入情况都使用运算符,而是要创建一个已接受答案的列表,然后您的条件将如下所示:while answer is not in accepted answers, ask another input
一个例子是:
Scanner scanner = new Scanner(System.in);
List<String> acceptedAnswers = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i");
String input;
do {
System.out.println(
"Please enter the location of your battleship, starting with the first letter value. Make sure it is from the letters a-i.");
input = scanner.nextLine();
} while (!acceptedAnswers.contains(input));
scanner.close();
System.out.println("Got correct input: " + input);