如何使一个数组的值成为另一个数组的索引?我正在尝试计算输入的不同整数。当我运行代码时,我收到索引越界消息。有什么想法吗?
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.
}
}
}
最佳答案
由于您越界,您将收到索引越界异常。
您需要从 count.length - 1
开始循环,而不是从 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?
您不能创建索引。您可以创建一个足够大的数组来包含您需要的所有索引。只需保留输入的最大值,然后创建一个此大小的数组即可。然后你就有了一个包含所有这些索引的数组。
处理这个问题的更好方法是使用 hashmap。键将是输入,值将是每个输入的计数器。这种方式比数组更好,因为每个不同的输入都有一个映射条目,仅此而已。使用数组,您最终会得到一个非常稀疏的数组,其中有许多“洞”。
关于java - 在 Java 中获取一个数组的值并使它们成为另一个数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49204881/