2013-04-07 85 views
0

如何將我的代碼中的緩衝讀取器更改爲Scanner,因爲我不允許使用BufferedReader?或者甚至有可能?文本文件Buffered Reader

public static void Option3Method() throws IOException 
{ 
    FileReader fr = new FileReader("wordlist.txt"); 
    BufferedReader br = new BufferedReader(fr); 
    String s; 
    String words[]=new String[500]; 
    String word = JOptionPane.showInputDialog("Enter a word to search for"); 
    while ((s=br.readLine())!=null) 
    { 
    int indexfound=s.indexOf(word); 
    if (indexfound>-1) 
    { 
     JOptionPane.showMessageDialog(null, "Word was found"); 
    } 
    else if (indexfound<-1) 
    { 
     JOptionPane.showMessageDialog(null, "Word was not found");} 
    } 
    fr.close(); 
    } 
} 

回答

1

更換

FileReader fr = new FileReader("wordlist.txt"); BufferedReader br = new BufferedReader(fr);

Scanner scan = new Scanner(new File("wordlist.txt"));

而更換

while ((s=br.readLine())!=null) {

while (scan.hasNext()) { 

      s=scan.nextLine(); 
     } 
+0

這給了我一個錯誤,然後說String s沒有定義? – user2205055 2013-04-07 15:31:10

+0

因此,聲明名爲's'的變量。我沒有給你完全烘焙的代碼,你可以直接在你的代碼中使用。這只是一個示例,它指示現有代碼的哪一部分需要更改以及如何更改。 – 2013-04-07 15:35:46

0

如果你看一下掃描儀類,你可以看到它有一個構造函數一個文件,這反過來又可以用字符串路徑被實例化。 Scanner類具有與readLine()(即nextLine())類似的方法。

0

沒有測試它,但它應該工作。

public static void Option3Method() throws IOException 
{ 
    Scanner scan = new Scanner(new File("wordlist.txt")); 
    String s; 
    String words[]=new String[500]; 
    String word = JOptionPane.showInputDialog("Enter a word to search for"); 
    while (scan.hasNextLine()) 
    { 
    s = scan.nextLine(); 
    int indexfound=s.indexOf(word); 
    if (indexfound>-1) 
    { 
     JOptionPane.showMessageDialog(null, "Word was found"); 
    } 
    else if (indexfound<-1) 
    { 
     JOptionPane.showMessageDialog(null, "Word was not found");} 
    } 
    } 
} 
相關問題