<分区>
我想创建一个程序来显示字符串中某个字符的出现次数,并计算它们的数量。现在代码只计算字符数。
我想进行以下更改:
1) 如何让这个程序只计算一种类型的字符,比如 a
或 c
字符串 I love ice cream
.
2) 我如何也打印字符串中的字符,假设有两个 d
我的程序将首先显示 2 d
。
3) 对于 Scanner input = new Scanner(System.in);
部分,我在 eclipse 中遇到错误,说扫描仪无法解析为类型。
也可以随时对代码中需要改进的任何内容发表评论。基本上只需要一个简单的程序来显示字符串中的所有 C,然后计算字符串的出现次数。然后我想自己弄乱代码,更改它以便我可以学习 Java。
到目前为止,这是我的代码:
public class Count {
static final int MAX_CHAR = 256; //is this part even needed?
public static void countString(String str)
{
// Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int length = str.length();
// Initialize count array index
for (int i = 0; i < length; i++)
count[str.charAt(i)]++;
// Create an array of given String size
char ch[] = new char[str.length()];
for (int i = 0; i < length; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
System.out.println("Number of Occurrence of " +
str.charAt(i) + " is:" + count[str.charAt(i)]);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str);
}
}