gpt4 book ai didi

java - 使用方法在 Java 列表中搜索匹配项

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:55:26 24 4
gpt4 key购买 nike

我正在尝试创建一个程序,该程序将使用名为“bulletproof”的程序包从用户那里获取输入(已完成,工作正常),但是当我找到匹配项时出现无限循环错误。我有点不知所措,我觉得我不太理解为什么我的代码不起作用。我不是在寻找直接的答案,因为我正在努力学习这个,但我们将不胜感激任何帮助。谢谢,我的代码如下。

--编辑--我让程序工作了。谢谢大家的帮助,你们太棒了。

import bulletproof.*;

public class A26_1 {
public static void main(String[] args) {
BPScanner kb = new BPScanner();
String reservedWordToCheck = kb.getStringFromUser("Enter a word to see if it's reserved or enter leave: ");

System.out.println(ReservedWordChecker(reservedWordToCheck));
}

public static String ReservedWordChecker(String reservedWordToCheck) {
String[] table = {
"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const",
"continue", "default", "do", "double", "enum", "extends", "final", "finally", "float",
"for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native",
"new", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super",
"switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", "while"
};

while (true) {
if (reservedWordToCheck.equalsIgnoreCase("leave"))
break;
boolean found = false;

for (int i=0; i < table.length; i++) {
if (reservedWordToCheck.equalsIgnoreCase(table[i])) {
found = true;
break;
}
if (found)
System.out.println("Yeah, " + reservedWordToCheck + ", is reserved as a Java identifier.");
else
System.out.println("Nope, the word " + reservedWordToCheck + ", isn't reserved. Go hog wild.");
}
System.out.println("OK BYE");
} return reservedWordToCheck;
}

最佳答案

我认为最简单的方法是 -

public static boolean ReservedWordChecker(String reservedWordToCheck) {
String[] table = {
"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const",
"continue", "default", "do", "double", "enum", "extends", "final", "finally", "float",
"for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native",
"new", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super",
"switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", "while"
};

for (String data : table) {
if (reservedWordToCheck.equalsIgnoreCase(data)) {
return true;
}
}
return false;
}

关于java - 使用方法在 Java 列表中搜索匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12928451/

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