2013-01-02 178 views
0

读我写的,增加了1到每次看到一个新字时调用totalint的方法:要从一个txt文件

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; 
} 

这是正确的方式来写呢?

+2

它会编译吗?你是如何试图测试它的? – Davidann

+0

更好的方式来做到这一点。 http://stackoverflow.com/a/4094186/628943 –

+0

问题是,这将有一个无限循环。考虑看客户是否在等待服务的隐喻,但你永远不会真正服务他们。 – Moshe

回答

5

看起来很好。但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; 
} 
+2

你确定,它是正确的吗? – ggcodes

+0

笏你认为它错了。 – Jayamohan

+1

您可以在我的答案中看到,在hasNext()中始终使用正则表达式作为参数。 –

2

扫描仪实现Iterator.You至少应该让迭代器向前迈出一步,这样的:

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; 

}

或循环将无限运行。

0

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

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

正如其他人所说,你有一个无限循环。还有一种更简单的方式来使用扫描仪。

int total = 0; 
    Scanner s = new Scanner(new File("/usr/share/dict/words")); 

    while(s.hasNext()){ 
     s.next(); 
     total++; 
    } 
    return total;