2016-12-02 57 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