0

我如何将代码中的 befferedreader 更改为 Scanner,因为我不允许使用 BufferedReader?还是有可能?

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();
   }
}
4

4 回答 4

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();
        }
于 2013-04-07T15:25:49.187 回答
0

您可以使用获取文件的扫描仪构造函数,然后使用nextLine()使用该扫描仪读取行。要检查是否还有更多行要读取,请使用hasNextLine()

于 2013-04-07T15:27:09.853 回答
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");}
     }
   }
}
于 2013-04-07T15:30:10.253 回答
0

如果您查看 Scanner 类,您会发现它有一个构造函数,该构造函数接受一个 File,而后者又可以使用 String 路径进行实例化。Scanner 类有一个类似于 readLine() 的方法,即 nextLine()。

于 2013-04-07T15:26:25.330 回答