我试图找到一个特定的点,从位置0开始计数。继承人是我到目前为止有:如何创建一个变量来保存文本文件中的所有数据而不使用has.next方法?
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
”只有同时在循环的值。因此使我无法在循环之外使用它。谁能帮我?也许给我一些新的东西,我还没有尝试过呢?
在循环之前声明'word'? – Tetramputechture 2014-10-28 04:20:05
是的,但作为什么?如果我只声明没有任何东西,它将保持不变,并且在while循环期间仍然只有一个值 – 2014-10-28 04:20:41
正确的,就像你在循环外面声明count一样,把'word'放在循环后面的行上。这就是所谓的“范围”,顺带一提。 – markspace 2014-10-28 04:20:49