問題に取り組んでいますが、正しい情報を出力するのに苦労しています。
私がやろうとしているのは、ターゲット値のすべての出現を見つけて、それを新しい配列に入れて、ターゲット値のインデックスを出力することです。ターゲット値が見つからない場合、空の配列が返されます。 outputs {}
現在、エラーが発生しています。
findAll():
[I@349b688e
[I@46ed5d9d
java.lang.ArrayIndexOutOfBoundsException
出力は次のようになります。
outputs {0, 5}
outputs {}
public class FindIndex(){
public FindIndex() {
int a[] = {7, 8, 9, 9, 8, 7};
System.out.println("findAll(): ");
System.out.println(findAll(a, 7));
System.out.print(findAll(a, 2));
}
public int[] findAll(int a[], int num) {
int indexNum = 0;
int arrSize = 0;
// find all occurrence of the target number
for(int i = 0; i < a.length; i++) {
if(a[i] == num) {
arrSize++;
}
}
// create new array
int newArray[] = new int[arrSize];
for(int i = 0; i < a.length; i++) {
if(a[i] == num) {
newArray[indexNum] = i;
}
}
return newArray;
}
public void print(int a[]) {
System.out.print("{");
int i;
for(i = 0; i < a.length - 1; i++) {
System.out.print(a[i] + ", ");
}
if(a.length > 0) {
System.out.print(a[i]);
}
System.out.print("}\n");
}
}