Ryan
Ryan

Reputation: 49

Character occurrence in a txt file java

I'm writing a character occurrence counter in a txt file. I keep getting a result of 0 for my count when I run this:

  public double charPercent(String letter) {

        Scanner inputFile = new Scanner(theText);

        int charInText = 0;
        int count = 0;

        // counts all of the user identified character
        while(inputFile.hasNext()) {

            if (inputFile.next() == letter) {
                count += count;
            }

        }

        return count;
    }

Anyone see where I am going wrong?

Upvotes: 0

Views: 926

Answers (3)

iSeeJay
iSeeJay

Reputation: 863

This is because Scanner.next() will be returning entire words rather than characters. This means that the string from will rarely be the same as the single letter parameter(except for cases where the word is a single letter such as 'I' or 'A'). I also don't see the need for this line:

int charInText = 0;

as the variable is not being used.

Instead you could try something like this:

 public double charPercent(String letter) {

    Scanner inputFile = new Scanner(theText);

    int totalCount = 0;

    while(inputFile.hasNext()) {

        //Difference of the word with and without the given letter
        int occurencesInWord = inputFile.next().length() - inputFile.next().replace(letter, "").length();

        totalCount += occurencesInWord;

    }

    return totalCount;
}

By using the difference between the length of the word at inputFile.next() with and without the letter, you will know the number of times the letter occurs in that specific word. This is added to the total count and repeated for all words in the txt.

Upvotes: 1

Abigail Fox
Abigail Fox

Reputation: 1681

Do you mean to compare the entire next word to your desired letter?

inputFile.next() will return the next String, delimited by whitespace (tab, enter, spacebar). Unless your file only contains singular letters all separated by spaces, your code won't be able to find all the occurrences of letters in those words.

You might want to try calling inputFile.next() to get the next String, and then breaking that String down into a charArray. From there, you can iterate through the charArray (think for loops) to find the desired character. As a commenter mentioned, you don't want to use == to compare two Strings, but you can use it to compare two characters. If the character from the charArray of your String matches your desired character, then try count++ to increment your counter by 1.

Upvotes: 0

SkrewEverything
SkrewEverything

Reputation: 2523

use inputFile.next().equals(letter) instead of inputFile.next() == letter1.

Because == checks for the references. You should check the contents of the String object. So use equals() of String

And as said in comments change count += count to count +=1 or count++.

Read here for more explanation.

Upvotes: 0

Related Questions