我试图找到一个特定的点,从位置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
"在循环中只有一个值。因此,我无法在循环外使用它。谁能帮我?也许给我一些我还没试过的新东西?
答案 0 :(得分:0)
String word = reader.next() + " ";
您已宣布" word
"在你的while块中。因此,系统只有在循环内部时才知道这个变量,一旦它在循环之外就会忘记它。如果要在循环外使用变量,则应在外部声明它。我知道你尝试过一次。现在,为什么单词在循环之外具有相同的值,即使在此之后呢? " word
"获取文件中的值,读者通过reader.next()
提供。因此,一旦你在循环之外,它仍将具有提供的最后一个值reader.next()
。如果要查看单词的值,只需在为其赋值后立即给出打印语句。
String word="";
while ( reader.hasNextLine()){
word = reader.next() + " ";
System.out.println("Word:"+word);
|
|
|
}
注意:如果您希望word
变量保存文件的整个单词,请执行此操作。
word=word+reader.next();
答案 1 :(得分:0)
尝试使用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
组合,如果您想查找所有字词的出现情况会更容易。