如何在数组中找到给定int的每个索引?

时间:2015-01-11 17:06:19

标签: java arrays int max

我试图在此数组中找到给定索引“max”的每一个匹配项,并确认只有一个索引具有给定值max。

    for ( int i = 0; i < posNum; i++) {
        if ( possibilitynum[i] > max) {
            max = possibilitynum[i];
        }
    }

    if (Arrays.asList(possibilitynum).lastIndexOf(max) != Arrays.asList(possibilitynum).indexOf(max)) {
        String[] button = { possibilities[Arrays.asList(possibilitynum).indexOf(max)].substring(possibilities[Arrays.asList(possibilitynum).indexOf(max)].length()-(possibilities[Arrays.asList(possibilitynum).indexOf(max)].length()-36-(main.category.length()))), possibilities[Arrays.asList(possibilitynum).lastIndexOf(max)].substring(possibilities[Arrays.asList(possibilitynum).lastIndexOf(max)].length()-(possibilities[Arrays.asList(possibilitynum).lastIndexOf(max)].length()-36-(main.category.length())))};
        int choice=JOptionPane.showOptionDialog(null, "Two items have "+max+" of the keywords you entered! Which item is correct?", "NEED INPUT ASAP",
                JOptionPane.WARNING_MESSAGE, 0, null, button, null);

    } else {
        main.theActualLink=possibilities[Arrays.asList(possibilitynum).indexOf(max)];
    }

Max出现多次,因此Arrays.asList(probabilitynum).indexOf(max)只会返回第一个索引,而我需要所有这些索引。 Arrays.asList(possiblenum).lastIndexOf(max)只会返回最后一个,所以我能找到两个索引,但不是全部。提前致谢

1 个答案:

答案 0 :(得分:2)

如果我理解您的问题,那么我认为最简单的解决方案是在现有的count循环中添加for。像

这样的东西
int count = 0;
for ( int i = 0; i < posNum; i++) {
    if ( possibilitynum[i] > max) {
        max = possibilitynum[i];
        count = 1;
    } else if (possibilitynum[i] == max) {
        count++;
    }
}

修改

如果您确实要存储索引,可以将它们添加到List之类的

List<Integer> maxIndexes = new ArrayList<>();
for ( int i = 0; i < posNum; i++) {
    if ( possibilitynum[i] > max) {
        max = possibilitynum[i];
        maxIndexes.clear();
        maxIndexes.add(i);
    } else if (possibilitynum[i] == max) {
        maxIndexes.add(i);
    }
}
int count = maxIndexes.size(); // <-- for example