2013-04-07 83 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");} 
    } 
    } 
} 
相关问题