我正在用於查找是否存在一行文本中的信對2個字母,例如,如果「AA」被輸入時,我會加1字母的程序[0] [0]。當我試着輸入「爲aabbcc」我得到這個錯誤:OutOfBounds異常與2D陣列
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 32
at Freq.processLine(Freq.java:25)
at Freq.main(Freq.java:12)
當我輸入「AABBCC」我得到這個錯誤:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.charAt(String.java:658)
at Freq.processLine(Freq.java:23)
at Freq.main(Freq.java:12)
我不知道爲什麼我收到這些錯誤。任何幫助將不勝感激。這裏是我的代碼:
import java.util.Scanner;
public class Freq{
private static final int ROWS = 26;
private static final int COLS = 26;
private static int[] [] alphabet = new int[ROWS][COLS];
public static void main(String[] args) {
String line;
Scanner userInput = new Scanner(System.in);
while(userInput.hasNextLine()) {
line = userInput.nextLine();
processLine(line);
}
}
public static void processLine(String line) {
line.toUpperCase();
for(int i = 0; i < alphabet.length; i++) {
for(int j = 0; j < alphabet[i].length; j++) {
for (int a = 0; a < line.length(); a++) {
char firstLetter = line.charAt(a);
char secondLetter = line.charAt(a + 1);
if (firstLetter == secondLetter) {
alphabet[firstLetter - 65][secondLetter - 65] = alphabet[firstLetter - 65][secondLetter - 65] + 1;
}
}
}
}
for (int b = 0; b < alphabet.length; b++) {
for (int c = 0; c < alphabet[b].length; c++){
System.out.print(alphabet[b][c] + " ");
System.out.println();
}
}
}
}
保佑你的靈魂 – Coder117