Oto mój kod:Array Index Out of Bounds Exception (Java)
public class countChar {
public static void main(String[] args) {
int i;
String userInput = new String();
userInput = Input.getString("Please enter a sentence");
int[] total = totalChars(userInput.toLowerCase());
for (i = 0; i < total.length; i++);
{
if (total[i] != 0) {
System.out.println("Letter" + (char) ('a' + i) + " count =" + total[i]);
}
}
}
public static int[] totalChars(String userInput) {
int[] total = new int[26];
int i;
for (i = 0; i < userInput.length(); i++) {
if (Character.isLetter(userInput.charAt(i))) {
total[userInput.charAt(i) - 'a']++;
}
}
return total;
}
}
Celem programu jest zwrócenie użytkownikowi na sznurku, a następnie policzyć, ile razy każdy znak jest używany w ciągu .
Kiedy idę do kompilacji programu, działa dobrze. Kiedy uruchamiam program, jestem w stanie wejść ciąg w oknie popup, ale po złożeniu łańcuch i naciśnij przycisk OK, pojawia się błąd, mówiąc
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 26
at countChar.main(countChar.java:14)
nie jestem całkowicie pewien, co problem jest i jak to naprawić.
Myślę, że pętla 'for' powinna zawrzeć instrukcję' if', a ';' na końcu jest niepoprawne. –
Czy możesz wskazać, która linia jest linią 14? (Użyj tutaj '// <- ArrayIndexOutOfBoundsException") – Stewart