for 循环错误 - 尝试使用循环来计算字母的重复次数
Error on the for loop - trying to use loop to count the repetition of letter
在 for 循环中,Java 小程序显示我有一个错误。我正在尝试使用 for 循环来计算字母的重复次数。
String countString = "";
for (int i = 0; i < 26; i++){
// at the line below, my java applet says I have an error, and that the
//"letterCounts" should be a int and not a string, but I need it to be a string
String n = letterCounts[i];
if (n.equals("0")) {
countString = countString + " ";
} else if (n.length() == 1) {
countString = countString + " " + n + " ";
} else {
countString = countString + n + " ";
}
}
this.countLabel.setText(countString);
你没有显示 letterCounts
的定义,但我敢打赌它是 int[] letterCounts
。
因此,由于 letterCounts
是 int
的数组,您不能将其分配给 String
。
只需将 String n
更改为 int n
并将您与 n == 0
的比较即可,它应该有效。见下文:
String countString = "";
for (int i = 0; i < 26; i++)
{
int n = letterCounts[i];
if (n == 0) {
countString = countString + " ";
} else if (n < 10) {
countString = countString + " " + n + " ";
} else {
countString = countString + n + " ";
}
}
this.countLabel.setText(countString);
在 for 循环中,Java 小程序显示我有一个错误。我正在尝试使用 for 循环来计算字母的重复次数。
String countString = "";
for (int i = 0; i < 26; i++){
// at the line below, my java applet says I have an error, and that the
//"letterCounts" should be a int and not a string, but I need it to be a string
String n = letterCounts[i];
if (n.equals("0")) {
countString = countString + " ";
} else if (n.length() == 1) {
countString = countString + " " + n + " ";
} else {
countString = countString + n + " ";
}
}
this.countLabel.setText(countString);
你没有显示 letterCounts
的定义,但我敢打赌它是 int[] letterCounts
。
因此,由于 letterCounts
是 int
的数组,您不能将其分配给 String
。
只需将 String n
更改为 int n
并将您与 n == 0
的比较即可,它应该有效。见下文:
String countString = "";
for (int i = 0; i < 26; i++)
{
int n = letterCounts[i];
if (n == 0) {
countString = countString + " ";
} else if (n < 10) {
countString = countString + " " + n + " ";
} else {
countString = countString + n + " ";
}
}
this.countLabel.setText(countString);