This is from Sun’s tutorial’s exercise area so I suppose it is homework.
I know how to use a for loop to iterate the string, but I wish to learn arrays while I am at it and store them in so. This is what I got so far:
BufferedReader in = new BufferedReader(new FileReader("xanadu.txt"));
int c;
char letters[] = new char[27]; //26 + newline?
while((c = in.read()) != -1){
letters[(char)c] += 1; //store in index, so letters['a'] = 4 etc..
}
Now for some reason (works in other languages), it does not cast int c to charproperly, and it enters letters[110] or something in decimal ascii instead, of course that is out of bounds of my array.
What way should I tackle THAT problem so I can have a nice index of chars?
Well, first of all,
System.out.println((int) 'A');will not give you0or1, it will give you 65, so you should at least doletters[(char) c - 'A'] += 1.Still though, you have only considered 27 letters, which only includes lower case? or upper case? no spaces? and so on…
You probably want to do something like