因此,我正在处理一个项目,该项目要求我将用户输入与txt文件中的单词列表进行比较。我一直在尝试将输入作为字符串与BufferReader进行比较,但一直不起作用。欢迎提出任何建议。
以下是该项目的代码
public class Lab5Program1 {
public static void main(String[] args) throws IOException {
File file = new File("fileName");
BufferedReader br = new BufferedReader(new FileReader(file));
/** In order to read a text file that is inside the package, you need to call the actual file and then pass it
* to the BufferedReader. So that it can be used in the file**/
// String[] wordArray = { "hello", "goodbye", "cat", "dog", "red", "green", "sun", "moon" };
String isOrIsNot, inputWord;
// This line asks the user for input by popping out a single window
// with text input
inputWord = JOptionPane.showInputDialog(null, "Enter a word in all lower case:");
// if the inputWord is contained within wordArray return true
if (wordIsThere(inputWord, br))
isOrIsNot = "is"; // set to is if the word is on the list
else
isOrIsNot = "is not"; // set to is not if the word is not on the list
// Output to a JOptionPane window whether the word is on the list or not
JOptionPane.showMessageDialog(null, "The word " + inputWord + " " + isOrIsNot + " on the list.");
} //main
public static boolean wordIsThere(String findMe, BufferedReader bufferedReader) throws IOException {
// for (int i = 0; i < bufferedReader.lines() ; i++){
// if (findMe.equals(theList[i])){
// return true;
// }
// }
while((findMe = bufferedReader.readLine()) != null) {
if (findMe.equals(bufferedReader.readLine())){
return true;
}
}
return false;
} // wordIsThere
}发布于 2021-09-17 15:16:37
错误来自检查单词是否存在的函数。未使用findMe检查文本文件中读取器的每一行。做了这些改变,它起作用了。
public static boolean wordIsThere(String findMe, BufferedReader br) throws IOException {
for (String word = br.readLine() ; word != null; word = br.readLine()) {
if (word.equals(findMe))
return true;
}
return false;
} 发布于 2021-09-17 15:12:30
在方法wordIsThere中,参数findMe是您要查找的单词。但是,您可以使用从文件中读取的行覆盖该参数的值。
您应该声明一个单独的变量来存储从文件中读取的文本行。
public static boolean wordIsThere(String findMe, BufferedReader bufferedReader) throws IOException {
String line = bufferedReader.readLine(); // read first line of file
while(line != null) {
if (findMe.equals(line)){
return true;
}
line = bufferedReader.readLine(); // read next line of file
}
return false;
}还要注意,由于您使用JOptionPane来获取用户输入,因此将启动一个单独的线程,并且该线程不会在方法main终止时终止。因此,您应该在类Lab5Program1中的main的最后一行调用类java.lang.System的方法exit。否则,每次运行类Lab5Program1时,都会启动一个新的不会终止的JVM。
对于控制台应用程序,您可以使用类java.util.Scanner来获取用户输入。
Scanner stdin = new Scanner(System.in);
System.out.print("Enter a word in all lower case: ");
String inputWord = stdin.nextLine();还可以考虑在使用完文件后将其关闭。在您的例子中,这是不必要的,因为当JVM终止时,文件会自动关闭。
https://stackoverflow.com/questions/69225453
复制相似问题