简体   繁体   中英

Why my outer loop doesn't increment to the next element of an array?

I have two nested loops, the outer one read from an array of the alphabet (AZ) and compares it to chars it read from a file. It is supposed to write to a different file the letter from the alphabet and the number of times it is mentioned in the file. So this is it:

for(int i = 0; i<alph.length; i++)
        {
            int count = 0;

            for(;;)
            {
                try {
                    c = reader.read();

                } catch (IOException e) {

                    e.printStackTrace();
                }//end of catch

                if(c==-1)
                    break;

                if(alph[i] == (char) c)
                {

                    count++;

                }


            }//end of endless loop

            writer.println(alph[i] + "  " + count);

        }//end of alphabet loop

The file it read from includes the phrase "JAVA STALE GUIDELINES." and it reads A to be mentioned 3 times and writes that fine. However, it doesn't go to the next letter and the ones after ...etc.

The letter that reaches this bit is just A:

if(alph[i] == (char) c)
                {

                    count++;

                }

All other letters are written as 0.

This is the end result:

A 3 B 0 C 0 D 0 E 0 F 0 G 0 H 0 I 0 J 0 K 0 L 0 M 0 N 0 O 0 P 0 Q 0 R 0 S 0 T 0 U 0 V 0 W 0 X 0 Y 0 Z 0

The problem is that the reader object is at the very end of the file after the first loop. You need call reader.reset() at the start of the loop to move it back to the beginning of the file.

It'd be better to move the file reader to the outer loop and the alphabet to the inner one, though, as reading the same file over and over isn't very efficient.

You only read the file once so it exits after counting instances of the first letter 'A'. You could put your alphabet in a map with an integer for count and use Arrays.asList(alpha).contains(c) and increment count for that letter in the map if it is contained in the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM