我試圖找到一個特定的點,從位置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