我正在学习java,这段代码存在一个错误。我根本不知道如何解决它。
以下是代码:
public class CountLettersInArray {
public static void main(String[] args) {
char[] chars = createArray();
System.out.println("The lowercase letters are:");
displayArray(chars);
int[] counts = countLetters(chars);
System.out.println(" ");
System.out.println("The occurence of each letter are: ");
displayCounts(counts);
}
public static void displayCounts(int[] counts) {
for (int i = 0; i < counts.length; i++);
if ((i + 1) % 10 == 0);
System.out.println(counts[i] + " " + (char)(i + 'a'));
else
System.out.println(counts[i] + " " + (char)(i + 'a') + " ");
}
public static int[] countLetters(char[] chars) {
//Declare and create an array of 26 int
int[] counts = new int[26];
//For each lowercase letter in the array, count it
for (int i = 0; i < chars.length; i++);
counts[chars[i] - 'a']++;
return counts;
}
public static void displayArray(char[] chars) {
//Display the characters in the array 20/line
for (int i = 0; i < chars.length; i++);
if ((i + 1) % 20 == 0)
System.out.println(chars[i]);
else
System.out.print(chars[i] + " ");
}
public static char[] createArray() {
//Declare the array of characters and create it
char[] chars = new char[100];
//Create lowercase characters randomly and assign them to array
for (int i = 0; i < chars.length; i++);
chars[i] = RamdomCharacter.getRandomLowerCaseLetter();
//This return the array
return chars;
}
}
我用Eclypse编写代码,软件告诉我这两件事:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
i cannot be resolved to a variable
RamdomCharacter cannot be resolved
我如何解决此问题?
答案 0 :(得分:2)
你将;
放在循环的末尾:
for (int i = 0; i < counts.length; i++);
^
摆脱它们,用{}
围绕循环体。
现在的问题是i
在循环范围内仅存在 。但是,您已经通过添加;
来终止循环范围,因此当您在外部引用i
时会收到编译错误。
答案 1 :(得分:1)
您指的是课程RamdomCharacter
。
RandomCharacter
答案 2 :(得分:0)
for (int i = 0; i < chars.length; i++); <--- remove the ;
counts[chars[i] - 'a']++;
;
结束陈述。因此,counts[chars[i] - 'a']++;
并未像您期望的那样封装在for循环中。因此,它无法访问i
变量。
{}
封装你的循环答案 3 :(得分:0)
对于第二个问题,我没有看到RamdomCharacter
类的定义位置,但我的猜测是它实际上称为RandomCharacter
,n
答案 4 :(得分:0)
除了其他两个答案所指出的问题外,RamdomCharacter似乎没有正确导入。这就是为什么你会遇到这样的错误。正确导入课程。