【发布时间】:2016-12-08 23:33:45
【问题描述】:
所以我有一个包含 30 个概率值的数组作为两倍。我想要
- 首先检查数组中的最高元素
- 将其索引存储在新数组中
- 重复第一步,排除之前检查过的元素
我试图通过将选中的元素替换为 null 并通过检查除 null 之外的所有元素来重复步骤 1 来做到这一点。但这给了我空指针异常。即使我正在创建 Array 的 Double 对象。
Double[] P_array= {0.23, 0.45, 0.1, 0.65, 0.67};
int maxIndex = 0;
int[] index_sorting = new int[P_array.length];
int sort_index = 0;
for (int i = 1; i < P_array.length; i++){
if (P_array[i] != (null)){ //getting NPE exception here
if ((P_array[i] > P_array[maxIndex])){
maxIndex = i;
System.out.print(new DecimalFormat("#0.00").format(P_array[i]));
System.out.print(",");
P_array[maxIndex]= null; //also getting NPE exception here
index_sorting[sort_index] = maxIndex;
sort_index++;
}
}
}
除了用 null 替换元素之外,还有什么更好的方法来完成任务?
【问题讨论】:
-
您在哪一行得到了异常?
-
那么,你想要一个索引数组,并让这个数组按照匹配的双精度值的降序排序,对吗?所以 [1.0, 2.0, 0.0] 会给出 [1, 0, 2]?
-
@reek 更新答案...
-
@JB 是的,我想要那样
-
在将 null 与 double 进行比较时,您可能会得到 npe。
标签: java arrays sorting nullpointerexception