我正在做一个作业,该作业要求读取文件并返回字母的频率。目前,我以return语句作为显示方法,以便文件中的字母显示在表格中,而这些字母的计数器在下一行。这是我的问题:我将显示方法嵌套在for循环中,该循环嵌套在while循环中,并且在读取文件后当前不返回任何内容。 while循环的构造使其仅在读取文件时才运行(文件的末尾为-1)。 for循环应该检查一下我的inputvalue的索引值是否与字母的索引值相同(如果是,则显示)。正如我已经提到的,它目前不显示任何内容。尽管进行了研究(并问了同学),但我仍然无法弄清问题所在。可以给出的任何见解将不胜感激。
final static int AlphabetSize = 26;
final static Scanner cin = new Scanner(System.in);
final static int MaxBarLength = 50;
public static void main(String[] args) {
String fileName;
// sign-on
out.print("CPS 150 Assignment 6 by Anthony Lapham \n\n");
// get the file name
out.print("Enter the file name: ");
fileName = cin.nextLine();
// process the file
try {
processFile(fileName);
} catch (FileNotFoundException e) {
out.println(fileName + " was not found,program terminated");
} catch (IOException e) {
out.println("Unforeseen IO exception,stack trace follows");
e.printStackTrace();
} // end try
// sign-off
out.print("\nAssignment 6 complete\n\n");
} // end main
static void processFile(final String fileName)
throws FileNotFoundException,IOException {
FileInputStream inFile = new FileInputStream(fileName);
int inputvalue = 0; // character read as an integer
char ch; // variable to hold input value typecast to char
int[] counters = new int[AlphabetSize];
final char[] alphabet = {'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'};
// declare other variables you need
int i;
// implement a standard sentinel control loop here
int SENTINEL = -1;
// read first input character as an integer
inputvalue = inFile.read();
while (inputvalue != SENTINEL) {
ch = (char) inputvalue;
for(i = 0; i < counters.length; i++){
if(char2int(ch) == alphabet[i]){
display(alphabet,counters);
}
}
// add code to process this character
// read next input character
inputvalue = inFile.read();
} // end loop
inFile.close();
// generate appropriate output
} // end function
static void display(final char[] alphabet,final int[] counters) {
// write code for this function
int counter = 0;
int charCounter;
int num;
out.print("The file has " + alphabet + " alphabetic,and " + counters + " other characters.\n\n");
out.println("Letter Count Bar");
out.println("------ ----- ---");
// while (counter < AlphabetSize) {
//// out.printf("%5s %-4s %-3s",alphabet,counters,printChars(counters,alphabet));
// counter++;
// }
} // end function
// char2int is complete
static int char2int(final char arg) {
if (!Character.isLetter(arg)) {
return -1;
} else {
return (int) Character.toUpperCase(arg) - (int) 'A';
}
} // end function
// function printChars writes n copies of the character c to the
// standard output device
static void printChars(final int n,final char c) {
// write the code
for (int i = 0; i < n; i++) {
if (i == char2int(c)) {
out.print("*");
}
}
} // end printChars
// this function returns the largest value stored in the array
static int maxCount(final int[] arr) {
// write the code
return 0;
} // end function
}