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
。