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,然后要求用户输入另一组字符,我输入a,b,c,d,y。它将退出程序并发出错误:- Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
。
答案 0 :(得分: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");
}