程序需要計算並顯示指定的charector出現在文本文件中的次數。計數字母出現
目前總數爲零。我不是如果我應該使用不同的循環,我也嘗試使用'for'循環。
// Hold user input and sum
String fileName; // Holds the name of the file
String letter; // Letter to search for in the file
int total = 0; // Holds the total number of characters in the file
// Get the name of the file and character from the user
fileName = JOptionPane.showInputDialog("Please enter the name of a file:");
letter = JOptionPane.showInputDialog("Please enter a letter contained in the string");
// Open the file for reading
File file = new File(fileName);
Scanner inputFile = new Scanner(file); // Declare new scanner object for file reading
// Set accumulator to zero
int count = 0;
if (inputFile.nextLine().equalsIgnoreCase(letter)) {
count++; // add letter occurrence
total += count; // add the letter occurrence to the total
}
是每行只有一個字母? – RNJ 2013-02-22 09:47:13
每一行都是一個單詞,.txt是一個段落 – 2013-02-22 09:57:08