如何在不使用has.next方法的情况下创建一个将所有数据保存在文本文件中的变量



我正试图找到一个特定的点,从单词出现的位置0开始计数。以下是我目前所拥有的:

import java.util.Scanner;
import java.io.*;
public class SearchFile {  
    public static void main ( String [] args ) throws IOException {
        int count = 0;

        File text = new File ( "TEXT.txt" ); //Makes new object of File Class called text and creates     a text document called whatever they want
        Scanner reader = new Scanner ( text ); //makes object of Scanner class called reader to read from the text file
        Scanner finder = new Scanner ( System.in ); //makes object of Scanner class called finder to store input
        System.out.print ( "Please enter a file name: ");
        String name = finder.nextLine();
        System.out.print ( "Please enter a word you want me to search for: " );
        String check = finder.nextLine();
        while ( reader.hasNextLine()){
            String word = reader.next() + " ";
            if ( word.equalsIgnoreCase ( check )){
               System.out.println ( "Searching in file name: " + name + "...nThe word " + check + " occurs " + count + " time in the text file." );
                count++;  
            }
        }
        if (count > 0) {
            int occurs = word.indexOf(check);
            System.out.println ( "The word " + check + " occurs first at index " + occurs + ".");    
        }
        if ( count == 0 ){
            System.out.println ( "Sorry! Unable to find word" );
            return;
        }
    }
}

我遇到的问题是,我的"word"在循环中只有一个值。因此,我无法在循环之外使用它。有人能帮我吗?也许给我一些我还没试过的新东西?

String word = reader.next() + " ";

您已经在while块中声明了"word"。因此,系统只有当这个变量在循环内时才知道它,一旦它在循环外,它就会忘记它。如果你想在循环外使用这个变量,你应该在循环外声明它。我知道你试过一次。现在,为什么单词在循环外的值是相同的?"word"取读卡器通过reader.next()提供的文件中的值。因此,一旦您在循环之外,它仍然具有reader.next()提供的最后一个值。如果你想查看单词的值,只需在给它赋值后立即给出一个打印语句。

   String word="";
   while ( reader.hasNextLine()){
     word = reader.next() + " ";
     System.out.println("Word:"+word);
          |
          |
          |
     }

注意:如果希望word变量包含文件的全部单词,请执行此操作。

word=word+reader.next();

尝试使用Files类读取文件。此代码将在每行中找到第一次出现

Path path = Paths.get("path");
List<String> lines = Files.readAllLines(path);
int found = -1;
for (String line : lines)
    found = line.indexOf("word");

不要忘记替换路径和搜索词。

如果您想在整个文件中找到的第一个出现,请使用StringBuilder连接行:

StringBuilder sb = new StringBuilder();
for (String line : lines)
    sb.append(line);
found = sb.toString().indexOf("word");

或者在每行中查找与其之前的所有行的第一个

int loc = 0;
for (String line : lines) {
    if (line.indexOf("word") != -1);
        found = loc + line.indexOf("word");
    loc += line.length();
}

您也可以使用Pattern-Matcher组合,如果您想查找该单词的所有出现,则会更容易。

相关内容