我在哪里编辑此代码以从我的输入文件中找到每个单词的第一个字母,保持频率和百分比,而不是每个字符?例如,我可以在哪里实施charAt(0)
或者我需要更改/添加什么?
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class FirstWordLetters
{
public static void main(String[] args) throws FileNotFoundException
{
char[] capital = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
char[] small = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
//Input Scanner into the system
Scanner scan;
//2. Locate file using the scanner class - search to computer data location
try {
scan = new Scanner(new File("F:/programming principles/Programming Principles - PART B/enciphered.txt"));
} catch (Exception e) { //throw exception e (meaning prevent any runtime errors)
System.out.println("File not found");
return;
}
//3. Set up int's (to count, and for the complete count.)
//the aplhabet has 26 characters so the new int will be 26. The mem. space of the array.
int[] count = new int[26];
int completeTotal = 0;
//4. Start scanning the system
//Scan every line and notify user that each line has been read properly.
//each time line has been read store value in array and increment by one
while(scan.hasNextLine()) {
String line = scan.nextLine();
System.out.println("Line read: " + line);
char[] digit = line.toCharArray();
for(int i = 0; i < digit.length; i++) {
for(int j = 0; j < 26; j++) {
if(digit[i] == capital[j] || digit[i] == small[j]) {
count[j]++;
completeTotal = completeTotal + 1;
break;
}
}
}
}
//5. Display results
//Print the overall data - letter, frequency and percentage.
System.out.println("");
System.out.println("First Word Count"); //notify user of what has been counted? (full count)
for (int i = 0; i < 26; i++) //increment each letter frequency by one each time
{
System.out.print(" " + small[i]);
System.out.print(" " + count[i]);
//calculate and display percentage for the full count
if (count[i] > 0)
System.out.println(" " + (((float) count[i]/completeTotal)*100) + "%");
else
System.out.println(" 0%");
}
}
} //end of source code.