![](/img/trans.png)
[英]ArrayIndexOutOfBoundsException error in Java program, and I don't know how to fix it
[英]Bug java. I don't know how to fix it
我正在学习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
我该如何解决这个问题?
你在放;
在循环结束时:
for (int i = 0; i < counts.length; i++);
^
摆脱它们,并用{}
包围循环体。
现在的问题是, i
仅存在于循环范围内。 但是,您已经通过添加;
终止了循环范围;
,因此当您在外面引用i
,会收到编译错误。
您指的是RamdomCharacter
类。
RandomCharacter
for (int i = 0; i < chars.length; i++); <--- remove the ;
counts[chars[i] - 'a']++;
的;
结束声明。 因此, counts[chars[i] - 'a']++;
没有像您期望的那样封装在for循环中。 所以它无法访问i
变量。
{}
封装循环 对于第二个问题,我看不到RamdomCharacter
类的定义位置,但是我猜想它实际上是被称为RandomCharacter
,并且带有n
除了其他两个答案指出的问题外,RamdomCharacter似乎未正确导入。 这就是为什么您会收到这样的错误。 正确导入该类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.