计算字符串中的字母 Java [英] Count letters in a string Java
问题描述
我正在做一个作业,我必须编写一个程序来从用户那里读取一个字符串,并打印出字符串中出现次数的字母.例如Hello world",它应该打印出h=1 e=1 l=3 o=2 ... etc.",但我的只写hello world"和字母总数.我不能使用 hashmap 函数,只能使用数组.有人可以就如何从下面的书面代码继续获得我喜欢的功能给我一两个提示吗?我不明白如何将写入的输入保存在数组中.
I'm doing an assignment where I'll have to code a program to read in a string from user and print out the letters in the string with number of occurrences. E.g. "Hello world" in which it should print out "h=1 e=1 l=3 o=2 ... etc.", but mine only write "hello world" and the amount of letters in total. I can't use the hashmap function, only arrays. Can someone give me a hint or two on how to proceed from the written code below to get my preferred function? I don't understand exactly how to save the written input in array.
这是我目前的代码.
public class CountLetters {
public static void main( String[] args ) {
String input = JOptionPane.showInputDialog("Write a sentence." );
int amount = 0;
String output = "Amount of letters:\n";
for ( int i = 0; i < input.length(); i++ ) {
char letter = input.charAt(i);
amount++;
output = input;
}
output += "\n" + amount;
JOptionPane.showMessageDialog( null, output,
"Letters", JOptionPane.PLAIN_MESSAGE );
}
}
推荐答案
你不需要 26 个 switch
案例.只需用简单的代码来数字母:
You don't need 26 switch
cases. Just use simple code to count letter:
String input = userInput.toLowerCase();// Make your input toLowerCase.
int[] alphabetArray = new int[26];
for ( int i = 0; i < input.length(); i++ ) {
char ch= input.charAt(i);
int value = (int) ch;
if (value >= 97 && value <= 122){
alphabetArray[ch-'a']++;
}
}
完成计数操作后,将结果显示为:
After done count operation, than show your result as:
for (int i = 0; i < alphabetArray.length; i++) {
if(alphabetArray[i]>0){
char ch = (char) (i+97);
System.out.println(ch +" : "+alphabetArray[i]); //Show the result.
}
}
这篇关于计算字符串中的字母 Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!