Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^496) | One-Dimensional Arrays
public static voidmain(String[] args) throwsIOException
{
BufferedReader dataFile;
charletter;
int index;
int location;
String inString;
int[] letterCount = new int[26];
dataFile = new BufferedReader(new FileReader("Words.in"));
inString = dataFile.readLine(); // Priming read
while(inString != null)
{
for (location = 0; location < inString.length(); location++)
{
letter = inString.charAt(location);
if ((letter >= 'A' && letter <= 'Z') || (letter >= 'a' && letter <= 'z'))
{
// Convert letter to an index
index =(int)Character.toUpperCase(letter) – (int)'A';
// Increment counter
letterCount[index] = letterCount[index] + 1;
}
}
inString = dataFile.readLine(); // Get a line
}
// Write the character and the count on the screen
for (index = 0; index < letterCount.length; index++)
System.out.println("The number of "+
(char)(index + (int)'A') + "'s is "+ letterCount[index]);
dataFile.close();
}
}
Here are the first and last paragraphs of the input, followed by the output:

Free download pdf