Reputation: 23
How can I make the values of an array the index of another array? I am trying to count the different integers that were entered. When I run the code, I am getting an index out of bounds message. Any thoughts?
import java.util.Scanner;
public class MatchineNums{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] arr = new int[4];
System.out.print("Enter 4 numbers: ");
for(int i = 0; i < arr.length; i++){
arr[i] = input.nextInt();
}
int[] count = new int[arr.length];
for(int i = count.length; i > -1; i--){
int value = arr[i];
count[value]++; //I think my problem is here but can't figure out why.
}
}
}
Upvotes: 0
Views: 981
Reputation: 2616
You're getting index out of bounds exception because you're out-of-bound.
You need to start your loop from count.length - 1
, not from count.length
.
for (int i = count.length - 1; i > -1; i--) {...}
How can I make the values of an array the index of another array?
You cannot make indices. You can create an array big enough to have all the indices you need. Just keep the maximum value of your inputs and then create an array this size. Then you have an array with all these indices.
A better way to handle this problem is to use a hashmap. The keys will be the inputs and the values will be the counter of each of them. This way is better than an array because you have a map entry for each different input and that's it. Using an array you'll end up having a really sparse array with many "holes".
Upvotes: 2