Reputation: 11
I have an array of the alphabet and say if the user has the letter A, then using this method the users' letter will change from A to B.
public class Letter {
private char letter;
public Letter(){
letter = 'A';
}
public char volgende(){
char[] alfabet = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
for (int i=0; i <= alfabet.length-1 ; i++) {
if (alfabet[i] == letter){
letter = alfabet[i++];
}
}
System.out.println("Nieuwe letter is " + letter);
return letter;
}
I expected this code to turn the default letter A to B, but it doesn't. I've tried replacing the alfabet[i++] with a char 'B', but that works, so i dont know why alfabet[i++] wouldn't, since it's the next item in the array.
Upvotes: 0
Views: 57
Reputation: 37604
You are using the post increment operator. You need to use the pre increment operator e.g.
letter = alfabet[++i]
By the way it is spelled alphabet and keep in mind that Z
will result in an IndexOutOfBoundsException error since it is the last index.
Upvotes: 2