Reputation: 69
I'm learning java and there's a bug into this code. I simply don't know howto fix it.
Here's the code:
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;
}
}
I'm coding it with Eclypse and the software is telling me those two things:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
i cannot be resolved to a variable
RamdomCharacter cannot be resolved
How am I supose to fix this?
Upvotes: 0
Views: 169
Reputation: 54682
apart from the problems noted by other two answer it seems RamdomCharacter is not imported properly. Thats why you are getting such error. import the class properly.
Upvotes: 0
Reputation: 69663
You are referring to a class RamdomCharacter
.
RandomCharacter
Upvotes: 1
Reputation: 31194
For you second issue, I don't see where the RamdomCharacter
class is defined, but my guess would be that it's actually called RandomCharacter
, with an n
Upvotes: 0
Reputation: 209004
for (int i = 0; i < chars.length; i++); <--- remove the ;
counts[chars[i] - 'a']++;
The ;
ends a statement. Therefore the counts[chars[i] - 'a']++;
is not encapsulated in the for loop as you'd expect. So it can't access that i
variable.
{}
to encapsulate your loopsUpvotes: 0
Reputation: 129517
You're putting ;
s at the end of your loops:
for (int i = 0; i < counts.length; i++);
^
Get rid of those, and surround the loop bodies with {}
.
The problem right now is that i
exists only in the scope of the loop. But, you've terminated the loop scope by adding the ;
, so when you reference i
outside you receive a compilation error.
Upvotes: 2