Hello, I'm having trouble coding a program which reads in strings (search terms) from a file, orders them, and then creates a histogram showing the occurrence of each string length.
For example, if the search terms were: frog, cat, dog; the program would print the following output:
Search Terms
-------------
frog
cat
dog
Term Length ... Count
------------ ... ------
3 .................... 2
4 .................... 1
I have the program reading in terms and sorting them, but I can't get the histogram to display the number of occurrences for each term.
I get output like this:
3 .......... 1
3 .......... 1
4 .......... 1
I know it's a logic error, but what should I be doing?
package nicepackage; import java.io.*; import java.util.Scanner; public class Search { /** * @param args */ public static void main(String[] args) throws Exception { System.out.println("\nSearch Terms"); System.out.print("------------"); FileReader fr1 = new FileReader("C:\\users\\T\\inSearchterms.txt"); Scanner inFr1 = new Scanner (fr1); int n = inFr1.nextInt()+1; String[] a = new String[n]; for (int i=0; i<n; i++) { a[i]= inFr1.nextLine(); //System.out.println(a[i]); } selectionSort(a); System.out.println("\nTerm Length Count"); System.out.println("----------- -----"); int[] histogram = new int[n]; int[] ct = new int[n]; for (int b=1; b <= a.length-1; b++) { for (int d = 30; d >= 0; d--) { if (d == a[b].length()) { histogram[b] = a[b].length(); ct[b]++; } } System.out.println(histogram[b] + " " + ct[b]); } } public static void selectionSort (String [] a) { for (int i=a.length-1; i >= 1; i--) { String currentMax = a[0]; int currentMaxIndex = 0; for (int j=1; j <= i; j++) { if (currentMax.compareToIgnoreCase(a[j])<0) { currentMax = a[j]; currentMaxIndex = j; } } if (currentMaxIndex != i) { a[currentMaxIndex] = a[i]; a[i] = currentMax; } //System.out.println("/"+a[i]); } } }
What am I doing wrong? Any help is greatly appreciated, thanks!