Java如何从文本文件中搜索单词
编辑:编写一个程序,从一个文件中读取100个字。然后,让用户搜索一个单词,直到他们输入“退出”。 该程序将从一个文件中读取最多100个字。文件可能包含也可能不包含100个单词,但数组最多只能容纳100个单词(如果列表中没有足够的单词,请用空字符串填充数组的其余部分)。 读入文件后,程序将提示用户输入搜索字符串。然后,程序将搜索字符串,并告诉用户是否找到该单词。程序将继续从用户处获取搜索字符串,直到用户输入“退出” 你好,我需要帮助编写一个程序从文本文件中找到一个单词 结果应该如下所示: 输入要搜索的单词:taco 找到了“塔可”这个词 输入要搜索的单词:asd 找不到单词“asd” 当用户输入单词“退出”时,程序将退出 下面是我到目前为止所做的,需要帮助才能完成Java如何从文本文件中搜索单词,java,Java,编辑:编写一个程序,从一个文件中读取100个字。然后,让用户搜索一个单词,直到他们输入“退出”。 该程序将从一个文件中读取最多100个字。文件可能包含也可能不包含100个单词,但数组最多只能容纳100个单词(如果列表中没有足够的单词,请用空字符串填充数组的其余部分)。 读入文件后,程序将提示用户输入搜索字符串。然后,程序将搜索字符串,并告诉用户是否找到该单词。程序将继续从用户处获取搜索字符串,直到用户输入“退出” 你好,我需要帮助编写一个程序从文本文件中找到一个单词 结果应该如下所示: 输入要搜
import java.io.*;
import java.util.Scanner;
public class project2 {
public static void main( String[] args ) throws IOException {
String[] list;
String search;
list = load_list( "words.txt" );
search = prompt_user( "\nEnter a word to search for: " );
while ( ! search.equals( "quit" ) ) {
System.out.println( "Word '" + search + "' was" +
( ( find_word( search, list ) ) ? "" : " NOT" ) +
" found." );
search = prompt_user( "\nEnter a word to search for: " );
}
System.out.println();
}
使用以下命令:
Scanner txtscan = new Scanner(new File("filename.txt"));
while(txtscan.hasNextLine()){
String str = txtscan.nextLine();
if(str.indexOf("word") != -1){
System.out.println("EXISTS");
}
}
下面的代码完美地回答了这个问题:
String word = ""; int val = 0;
while(!word.matches("quit"))
{
System.out.println("Enter the word to be searched for");
Scanner input = new Scanner(System.in);
word = input.next();
Scanner file = new Scanner(new File("newFile.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
if(line.indexOf(word) != -1)
{
System.out.println("Word EXISTS in the file");
val = 1;
break;
}
else
{
val = 0;
continue;
}
}
if(val == 0)
{
System.out.println("Word does not exist");
}
System.out.println("-------continue or quit--- enter continue or quit");
word = input.next();
}
到底是什么问题?另外,请向我们展示加载列表()和提示用户()的代码。您有什么问题?最好将
search.equals(“quit”)
写成“quit.equals”(搜索)
如果不使用break&continue语句,您将如何编写代码?@JimmyBob:使用break可以提高代码的效率,因为一旦找到单词,它就会退出,否则它将遍历所有行。。只需删除break和continue语句,代码就可以正常工作,但是在while循环if(val==1)System.out.println(“Word已找到”)之后添加这个if块;。您可以将其作为函数编写,并在if语句中返回
String word = ""; int val = 0;
while(!word.matches("quit"))
{
System.out.println("Enter the word to be searched for");
Scanner input = new Scanner(System.in);
word = input.next();
Scanner file = new Scanner(new File("newFile.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
if(line.indexOf(word) != -1)
{
System.out.println("Word EXISTS in the file");
val = 1;
break;
}
else
{
val = 0;
continue;
}
}
if(val == 0)
{
System.out.println("Word does not exist");
}
System.out.println("-------continue or quit--- enter continue or quit");
word = input.next();
}