I'm working on a program where I'm reading a file and I have to count the number of entries in the file. Each entry takes up a different number of lines, but each entry is also separated by a '#'. I'm wanting to read through the file and count the number of '#' marks first before I do anything, but I can't figure out how exactly to do it.

Here is what I have so far, and I keep getting an "incompatible types" error because i'm checking for characters and apparently # isn't a character, or i'm just doing something totally wrong. Is there some method I need to be calling to do this or what? I'm stuck, lol, HELP!!!

public static int scanFile(String test)throws IOException
        char mark = "#";
        int count=0;
        Scanner fin = new Scanner(new File(test));
            String line = fin.nextLine();
            for(int x=0; x<line.length(); x++)
                if(line.charAt(x) == mark)
                    count ++;
            }//end for    
        }//end while
        return count;
    }//end scanFile

I can make it work just fine if I count the number of lines in the file, just not for counting the #... I'm not really looking for an ANSWER, just maybe a tip, or point out something I'm overlooking.

9 Years
Discussion Span
Last Post by iamthwee

This is not very good practice line.charAt(x) == mark you should use Character methods compareTo() which return integer

the value 0 if the argument Character is equal to this Character; a value less than 0 if this Character is numerically less than the Character argument; and a value greater than 0 if this Character is numerically greater than the Character argument (unsigned comparison). Note that this is strictly a numerical comparison; it is not locale-dependent.

or you can use method equals() which return boolean

true if the objects are the same; false otherwise.

More info can be found in Charecter class API documentation here


actually, the comparing part wasn't the problem. It was not being able to compare the char type variable with the "#" that was assigned to the mark variable because of incompatible types...

Now that i've sat here messing with this for god knows how long, i look at the thing and I go... "Why is it telling me that the mark variable is a string?" Then I look at what I assigned it, ("#") and i go... oh yeah... double quotes IS a string. single quotes is a char. So then I felt really stupid for even posting this in the first place.... lol. I just changed

char mark = "#";


char mark = '#';

and everything worked just fine... LOL! I'm so dumb, haha. Always overlooking the obvious. Oh well.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.