我的问题是:
编写一个程序,提示用户输入文件名并显示文件中每个字母的出现次数。必须使用例外。字母不区分大小写。
以下是一个示例运行:
Enter the File name: example.txt
The Occurrence of A's is 11
The Occurrence of B's is 2
....
The Occurrence of Y's is 3
The Occurrence of Z's is 2.
我的代码被认为我必须区分大小写,而我不必这样做。那么如何更改我的代码以包含所有字母而不仅仅是大写字母。我自己没有太多时间来解决这个问题,这就是我在这里发布的原因:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class LetterOccurance
{
public static void main(String[] args) {
System.out.print("Enter file name: ");
File file = new File(new Scanner(System.in).next());
if (!file.exists())
{
System.out.println(file + " doesn't exist");
System.exit(1);
}
String buffer = "";
int[] letterCount = new int[26];
try (Scanner input = new Scanner(file))
{
while (input.hasNext())
{
buffer = input.nextLine();
for (char ch : buffer.toCharArray())
{
ch = Character.toUpperCase(ch);
if (isLetter(ch))
{
letterCount[ch - 'A']++;
}
}
}
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
for (int i = 0; i < letterCount.length; i++)
{
System.out.println((char)(i + 'A') + " occurrence = " + letterCount[i]);
}
}
private static boolean isLetter(char ch)
{
return (ch >= 'A' && ch <= 'Z');
}
}
答案 0 :(得分:0)
您可以选择使用大写或小写。无论您使用哪种方式,对于您正在查看的文本以及您要比较的文本,您都会这样做。所以你要对文件中的字符串执行toUpperCase()(或更低版本),然后查找大写(或小写)字母