I'm pretty new to Java and I've been trying to use top-down design and make my code very readable, so I would appreciate any comments as to the clarity and efficiency of this program.
Looking for feedback on: readability (spacing, comments, etc) and just overall quality of code!
The task is to produce a histogram that shows how many times a certain letter appears in a string.
import java.util.Scanner;
/** This class creates a histogram of the letters in a string. Ie outputs
** how many times the letter a appears in the string, the letter b... and so on
** until z. Extra challege: only traversing the string once
**/
public class Histogram{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
final int LETTERS_IN_ALPHABET = 26;
int[] letterCounter = new int[LETTERS_IN_ALPHABET]; //holds info on how many
//times a letter appears. eg letterCounter[0] -> how many times a appears
System.out.print("Enter string: ");
String string = kb.nextLine();
for(int i = 0; i < string.length(); i++){//traversing string
char letterThere = string.charAt(i);//reads what character is at index
int placeInLetterCtr = whereInLetterCtr(letterThere);//determining where it should go in array
letterCounter[placeInLetterCtr] ++;//increasing corresponsing index
}
printNumbers(letterCounter);
printLetters();
}//end main
/* given a char, determines at what index of the character storage array the
* char belongs to. Eg, if given the char 'c', it should return int 2
*/
public static int whereInLetterCtr(char letter){
int i =0 ;
for(char comparisonLetter = 'a'; comparisonLetter <= 'z'; comparisonLetter++){
if(letter == comparisonLetter){
return i;
}
i++;
}
return i;
}//end whereInLetterCtr
/* prints row of numbers */
public static void printNumbers(int[] array){
for(int i=0; i<array.length; i++){
System.out.printf("%4d", array[i]);
}
System.out.println();
}//end printNumbers
/* prints row of letters */
public static void printLetters(){
for(char letter ='a'; letter <='z'; letter++){
System.out.printf("%4c", letter);
}
}//end printLetters
}//end class