【问题标题】:Reading from a txt file从 txt 文件中读取
【发布时间】:2013-01-02 03:04:23
【问题描述】:

我写了一个方法,每次看到一个新单词时,都会在名为 totalint 上加 1:

public int GetTotal() throws FileNotFoundException{
    int total = 0;
    Scanner s = new Scanner(new BufferedReader(new FileReader("Particles/Names.txt")));
    while(s.hasNext()){
        if(s.hasNext()){
            total++;
        }
    }
    return total;
}

这样写对吗?

【问题讨论】:

  • 它可以编译吗?您是如何尝试测试的?
  • 更好的方法在这里。 stackoverflow.com/a/4094186/628943
  • 问题是,这会有一个无限循环。想想看客户是否在等待服务,但您从未真正为他们服务。
  • hasNext 方法不会从 Scanner 读取单词。您必须调用 next 方法从扫描仪中读取单词。

标签: java


【解决方案1】:

看起来不错。但是inner IF 是不必要的,next() 方法也是必需的。下面应该没问题。

public int GetTotal() throws FileNotFoundException{
    int total = 0;
    Scanner s = new Scanner(new BufferedReader(new FileReader("Particles/Names.txt")));
    while(s.hasNext()){
            s.next();
            total++;
    }
    return total;
}

【讨论】:

  • 如我的回答所示,您始终可以在 hasNext() 中使用正则表达式作为参数。
  • @Jayamohan 再次查看它,看看有什么问题。你可以仔细检查一下。
【解决方案2】:

扫描器实现了迭代器。你至少应该让迭代器向前迈出一步,像这样:

public int GetTotal() throws FileNotFoundException{
int total = 0;
Scanner s = new Scanner(new BufferedReader(new FileReader("Particles/Names.txt")));
while(s.hasNext()){
        s.next();
        total++;
}
return total;

}

否则循环将无限运行。

【讨论】:

    【解决方案3】:

    使用正则表达式匹配所有非空格。 :-)

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    
    public class ScanWords {
    
     public ScanWords() throws FileNotFoundException {
       Scanner scan = new Scanner(new File("path/to/file.txt"));
       int wordCount = 0;
       while (scan.hasNext("\\S+")) {
         scan.next();
         wordCount++;
       }
       System.out.printf("Word Count: %d", wordCount);
     }
    
     public static void main(String[] args) throws Exception {
        new ScanWords();
      }
    }
    

    【讨论】:

      【解决方案4】:

      正如其他人所说,您有一个无限循环。还有一种更简单的使用 Scanner 的方法。

          int total = 0;
          Scanner s = new Scanner(new File("/usr/share/dict/words"));
      
          while(s.hasNext()){
              s.next();
              total++;
          }
          return total;
      

      【讨论】:

        猜你喜欢
        • 2016-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-06
        • 2020-10-09
        • 2016-05-03
        相关资源
        最近更新 更多