0

Disclaimer: This question pertains to homework. I've been trying this for a little bit now and I've taken out most the stuff I've tried because it's just become redundant.My question is how do I count the number of "lines" in my file that have non ascii characters. I've found the way to count how many non-ascii characters occur. The line is stumping me though.

For instance, if a line in the file reads èèèèè, then movieCount should increase by 1 and my ascCount should increase by 5. Not all lines will have non-ascii characters though.

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

                            }
                    }

    }
akrutke
  • 11
  • 3

2 Answers2

2

Create a method that returns true if the line contains only ascii characters

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

In your main program:

 while ((empty = buffMovie.readLine()) != null){
        movieCount += (isAscii(empty) ? 1 : 0);
 }
Aimee Borda
  • 842
  • 2
  • 11
  • 22
0

You are increasing ascCount when you find non-ascii character but not increasing movieCount. So you have to increase movieCount also. Please use below code snippet:

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

This will increase movieCount only when non-ascii character is present and your non-ascii will increase as per your requireemnt.

Also I would suggest to use regex for checking non-ascii character. Read @Scary comment also.

SachinSarawgi
  • 2,632
  • 20
  • 28