Goal: To count the number of times each letter (a-z) is used in a file. The code is workin (atleast it appears to be), but I have a couple issues.
1. I am wanting the array to be initialized in the constructor but when I do that the other methods can't access is. Is there a way to make that work?
2. I am not sure how to reset the counter at the end in the resetInventory method
/* * Count the number of times a letter * * @author Kristen Watson * @version 11/12/2012 * */ import java.util.Scanner; import java.io.File; public class LetterInventory{ public final static String filename = "testFile.txt"; public void main(String[] args) { Scanner inputFile = null; try { inputFile = new Scanner(new File(filename)); } catch (Exception e) { System.out.println("File could not be opened: " + filename); System.exit(0); } countOccurrences(inputFile); displayTable(); } int[]counters = new int[26]; char current; int value; /* * constructor * inventory of letters with maximum of 26 different letters */ public LetterInventory(){ } /* * scanner takes information from the file and counts the letters */ public void countOccurrences(Scanner file) { while(file.hasNextLine()){ //take information one line at a time String line = file.nextLine(); //convert all letters in the string to lower case line.toLowerCase(); for(int i=0; i < line.length(); i++){ current = line.charAt(i); if (current >= 'a' && current <= 'z'){ //check that the char is a letter value = (int)(current - 'a'); counters[value]++; } } } } /* * output of the counted letters */ public void displayTable(){ for (int i = 0; i < counters.length; i++){ current = (char)(i + 'a'); System.out.println(current + ":" + counters[i]); } } public void resetInventory(){ } }
Gracias to anyone who can explain to me the error of my ways