Java: Find greatest number of occurrences of a letter

75 Views Asked by At

I am new to Java, so it would be great if you could keep things pretty basic for me.

I have calculated the percent occurrence of each letter of the alphabet. I want to find the letter with the greatest occurrences.

{ code to count occurrence of each letter }

      aCounter/=letterCounter; 
      bCounter/=letterCounter;
      cCounter/=letterCounter;
      dCounter/=letterCounter; 

      double largest = aCounter;
      char character = 'A';
      if  (bCounter > largest)
            largest = bCounter;
            character = 'B';
      if  (cCounter > largest)
            largest = cCounter;
            character = 'C';
      if  (dCounter > largest )
            largest = dCounter;
            character = 'D'

      System.out.printf ("%c %.2f",character, largest);  

This code is just printing D now.

Thank you all for the help!!

2

There are 2 best solutions below

1
On

You are missing braces :

    if  (bCounter > largest) {
        largest = bCounter;
        character = 'B';
    }
    if  (cCounter > largest) {
        largest = cCounter;
        character = 'C';
    }
    if  (dCounter > largest ) {
        largest = dCounter;
        character = 'D';
    }

Your character = ... statements were not part of the if conditions, so they were always executed, and since character = 'D'; was the last one, that was the character that was printed.

1
On
if  (dCounter > largest )
        largest = dCounter;
        character = 'D';

You need to have brackets here:

if  (dCounter > largest ){
        largest = dCounter;
        character = 'D';
}

Otherwise it parses as

if  (dCounter > largest )
        largest = dCounter;
character = 'D';

Save yourself a lot of trouble and use an IDE with code formatting. Automatic indentation would have made this obvious very quickly.