2013-01-02 175 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;