Reputation: 1
I have a program which takes a string and gives a histogram. The problem is i need the histogram to be in order... like... letter count a 0 b 1 c 0 .... etc. My program will just give back the letters in the string, it will not display the letters which are not in the string. here is my main program.
import java.util.*;
public class CharacterHistogram {
//scanner and method decleration
Scanner keyboard = new Scanner (System.in);
public static void generateHistogram( String input) {
// make input lower case
input=input.toLowerCase();
int lengthOfInput= input.length();
char[] Array = input.toCharArray();
//Arrays.sort(Array);
int count = 0;
// colum creation
System.out.println();
System.out.println(" Character Count");
for (int i = 0; i < lengthOfInput; i++) {
// reset count every new letter
count = 1;
for (int x = i + 1; x < lengthOfInput; x++) {
if (Array[i] == ' ') {
break;
}
if (Array[i] == Array[x]) {
count++;
Array[x] = ' ';
}
}
// check for empty char
if (Array[i] != ' ') {
System.out.println();
//row creation
System.out.println(" "+Array[i]+" "+count);
System.out.println();
}
}
}
}
here is the tester:
public class CharacterHistogramTester{
public static void main(String [] args){
String input = "4axaaafgaa5";
System.out.println("Generate Histogram for: " + input);
CharacterHistogram.generateHistogram(input);
input = " OSU won 34-10 and now have 7 wins";
System.out.println("Generate Histogram for: " + input);
CharacterHistogram.generateHistogram(input);
}
}
i would like to know if there are any ways to show all letters (even ones not used in string) alphabetically. Thank you.
P.S. i have tried the sort(Array) method and it screws up the whole program...
Upvotes: 0
Views: 1851
Reputation: 14164
Use a single loop to traverse the string & count letter/character occurrences, not the unnecessary & inefficient "loop within a loop" structure which you have currently.
Initialization, counting & printing the output should be separate blocks of code -- not mangled into the same block.
Upvotes: 1
Reputation: 691685
Create an int array of length 26, contaning the number of occurrences of each letter (0, initially).
Loop through each char of your input, and increment the integer at the appropriate index (0 for a, 1 for b, etc.).
Then print every element of the int array.
Oh, and respect the Java naming conventios: variables start with a lowercase letter.
Upvotes: 1