2016-12-02 52 views
0

免責聲明:此問題屬於作業。我一直在嘗試這一點,我已經拿出了我嘗試過的東西,因爲它只是變得冗餘。我的問題是如何計算我的文件中「非線性」的數量字符。我找到了計算有多少非ASCII字符出現的方法。儘管如此,這條路線仍在困擾着我。計算具有非asscii字符的文件的行數

例如,如果文件中的一行代碼是èèèèè,那麼movieCount應該增加1,我的ascCount應該增加5.不是所有行都會有非ascii字符。

 public static void main(String [] args) throws FileNotFoundException{ 

    //open the file 
    File movieFile = new File("/home/turing/t90rkf1/d470/dhw/hw5-movies/movie-names.txt"); 

    InputStream file = new FileInputStream(movieFile); 

    String empty = null; 
    int movieCount = 0; 
    int ascCount = 0; 

    try { 
      FileReader readFile = new FileReader(movieFile); 

      BufferedReader buffMovie = new BufferedReader(readFile); 


      //read while stream is not empty 
      while ((empty = buffMovie.readLine()) != null){ 

        //check the value for ascii 
        for(int j = 0, n = empty.length(); j < n; j++){ 

        char asc = empty.charAt(j); 

          if(asc > 127){ 

          ascCount++; 

          } 
        } 

    } 
+0

您正在增加ascCount而不是movieCount。 – SachinSarawgi

+0

也考慮使用正則表達式來定位非ASCII字符http://stackoverflow.com/questions/2124010/grep-regex-to-match-non-ascii-characters –

+1

爲什麼你要計算非ASCII字符? –

回答

2

創建如果行只包含ASCII字符

private static boolean isASCII(String s) 
{ 
    for (int i = 0; i < s.length(); i++) { 
     if (s.charAt(i) > 127) 
     return false; 
    } 
    return true; 
} 

在你的主程序返回true的方法:

while ((empty = buffMovie.readLine()) != null){ 
     movieCount += (isAscii(empty) ? 1 : 0); 
} 
+0

謝謝=)。即刻解決問題! – akrutke

+0

答案應該說明你現在迭代所有的字符兩次。 –

+1

您是否因爲解決方案讀取一行然後解析該行而不是一次讀取某個字符而引用? –

0

您正在增加ascCount當你發現非ASCII字符但不會增加movieCount。所以你也必須增加movieCount。請使用下面的代碼片段:

while ((empty = buffMovie.readLine()) != null){ 
//check the value for ascii 
boolean ifMovieCountPre = false; 
for(int j = 0, n = empty.length(); j < n; j++){ 
    char asc = empty.charAt(j); 
    if(asc > 127){ 
     ascCount++; 
     ifMovieCountPre = true; 
    } 
} 
if(ifMovieCountPre) 
     movieCount++; 
} 

這將增加movieCount只有當非ASCII字符存在,你的非ASCII會增加,按您的requireemnt。

此外,我會建議使用正則表達式檢查非ASCII字符。 閱讀@Scary評論也。

+0

@akrutke它解決你的問題?? – SachinSarawgi