Skip to content
Advertisement

Incorrect output when counting the occurence of each character in a given string (beginner Java)

I am trying to write a program that saves a string into an array and then gives the number of occurences for each of the characters in that string.

This is my code so far:

String string = "The quick brown fox jumps over the lazy dog";
string.toLowerCase();

int[] count = new int[26];
char[] vrstica = string.toCharArray();


for(char crka : vrstica){
    int indeks = ((int)('z') - (int)('a'));
    count[indeks]++;
}
    for(int i = 0; i < count.length; i++){
        if(count[i] != 0){
            System.out.println((char)('a'+ i) + " > " + count[i]);
        }
    }

and this is the output I am currently getting:

z > 43

I am using .toCharArray() because that was the tip given in the instructions for this assignment, but I am not completely sure if the way I am using it is correct.

Thank you for your help 🙂

Advertisement

Answer

Here are a few problem with your code.

string.toLowerCase();

toLowerCase returns the lower case of string, and doesn’t change the original string. You need to capture the returned string.

string = string.toLowerCase();

You need to change ((int)('z') to ((int)(crka).

You also need to handle the space character ‘ ‘.

Here’s are the changes:

String string = "The quick brown fox jumps over the lazy dog";
string = string.toLowerCase();  // <<<  change here

int[] count = new int[26];
char[] vrstica = string.toCharArray();


for(char crka : vrstica){
    int indeks = ((int)(crka) - (int)('a'));  // <<< change here
    if (crka != ' ') count[indeks]++;  // <<< change here
}

for(int i = 0; i < count.length; i++){
  if(count[i] != 0){
    System.out.println((char)('a'+ i) + " > " + count[i]);
  }
}
4 People found this is helpful
Advertisement