0
public class ParallelArray {

    public static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        char[] charArray = new char[5];
        int[] intArray = new int[5];
        char ch;
        int count;
        System.out.println("Enter 5 characters: ");
        for (int i = 0; i < charArray.length; i++) {
            charArray[i] = sc.next().charAt(0);
        }

        do {
            System.out.println("Enter a character: ");
            ch = sc.next().charAt(0);
            int location = search(ch, charArray);
            intArray[location]++;
            System.out.println("Again? 1-yes, 0-no");
            count = sc.nextInt();
        } while (count == 1);

        printBothLists(charArray, intArray);
    }

    public static void printBothLists(char[] charArray, int[] intArray) {
        for (int i = 0; i < charArray.length; i++) {
            System.out.println(charArray[i] + " - " + intArray[i]);
        }
    }

    public static int search(char ch, char[] charArray) {
        int count = -1;
        for (int i = 0; i < charArray.length; i++) {
            if (ch == charArray[i]) {
                count = i;
                return count;
            }
        }
        return count;
    }
}

如果我输入 5 个字符,a,b,c,d,e 作为数组,然后要求用户 t 输入另一组字符,我输入 a,b,c,d,y。它将退出程序并给出错误:- Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1

4

1 回答 1

2

您没有检查用户输入不存在的字符的可能性......

int location = search(ch, charArray);
intArray[location]++; // <-- The index is invalid...

您需要在尝试访问阵列之前进行检查...

int location = search(ch, charArray);
if (location >= 0 && location < intArray.length) {
    intArray[location]++; // <-- The index is invalid...
} else {
    System.out.println("'" + ch + "' does not exist");
}
于 2012-09-27T00:39:30.013 回答