我是Java编程的新手,我遇到了一个问题。我的问题是不是从文本文件返回一个句子,而只返回关键字。我进入了“谁今天过得愉快?”只返回“day”。让我们说一个文本文件包含“Paula今天过得愉快”我的目标是回归“Paula今天过得愉快”,这是我的代码。
问题在于parseFile方法和我的if语句,我调用了parseFile()
public static void parseFile(String s) throws FileNotFoundException {
File file = new File("today.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(s);
break;
}
}
}
this is my main
public static void main(String args[]) throws ParseException,
FileNotFoundException {
String[] keywords = { "day", "What book", "not going ", "okay"};
boolean endloop = false;
boolean found = false;
Scanner scanner = new Scanner(System.in);
String input = null;
System.out.println("What's up?");
do {
System.out.print(" - ");
input = scanner.nextLine().toLowerCase();
for (String keyword: keywords) {
if (input.contains(keyword)) {
//System.out.println("Found keyword!"+ keyword);
// TODO: You can optimize this
parseFile(keyword);
}
}
if (!found) {
System.out
.println("I am sorry I do not know");
}
break;
}
while (!input.equalsIgnoreCase("thanks"));
System.out.println(" Have a good day!");
}
} “today.txt”包含 宝拉度过了美好的一天。 卡拉问什么是好书。
非常感谢任何帮助
答案 0 :(得分:0)
您正在打印s,这是用于搜索的单词。你应该打印变量lineFromfile,因为它包含来自文件
的值public static void parseFile(String s) throws FileNotFoundException {
File file = new File("today.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile);
break;
}
}
}
答案 1 :(得分:0)
你在哪里
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(s);
break;
}
你打印出“s”,这是你要找的东西, 但你想打印出这条线。这是“lineFromFile” 所以你可能想做
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile);
break;
}