gpt4 book ai didi

java - 如何设置do循环条件 "when string does not equal"

转载 作者:行者123 更新时间:2023-12-02 04:24:37 26 4
gpt4 key购买 nike

我想让我的 do 循环在用户输入的输入不等于所需的字母 (a-i) 时运行。出于某种原因,即使我输入正确的字母,它也会永远循环。

我尝试在比较中使用 switch case 以及 != 。

这是我的代码:

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 技能有限,但这应该可行,除非我遗漏了一些明显的东西。任何帮助都会很棒!

最佳答案

您可能希望创建一个接受答案的列表,而不是对每种输入情况使用运算符,然后您的条件将如下所示:

当答案不在接受的答案中时,请询问另一个输入

一个例子是:

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);

关于java - 如何设置do循环条件 "when string does not equal",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56613000/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com