首页 > 解决方案 > 使用 Array 和 while 循环的询问数字的 Java 索引

问题描述

我如何在这里找到索引?我错过了什么吗?

public static void main(String[] args) {
    Scanner lukija = new Scanner(System.in);

    ArrayList<Integer> list = new ArrayList<>();
    while (true) {
        int red = Integer.valueOf(lukija.nextLine());
        if (red == -1) {
            break;
        }

        list.add(red);
    }

    System.out.println("");

    // toteuta tänne toiminnallisuus luvun etsimiseen
    int num = 0;
    int index = 0;
    int i = 0;

    while (index <= list.size()) {

        num = Integer.valueOf(lukija.nextLine());
        System.out.println("What are we looking for? " + num);

        i = list.get(index);

        break;

    }
    i++;
    index++;

    System.out.println("number " + num + " is in index " + i);
}

}

与:51 22 -11 -140 -18 -1 22

打印是:

我们在找什么?

22 数字 22 在索引 52 中

标签: javaarraylist

解决方案


如果您试图在 ArrayList 中查找值的索引,那么您应该使用该indexOf方法。Usingget将返回该索引处的元素。

所以你的代码看起来像这样:

while (index <= list.size()) {

    num = Integer.valueOf(lukija.nextLine());
    System.out.println("What are we looking for? " + num);

    // changes here
    i = list.indexOf(num);
    break;

}
i++;

注意:不确定为什么在返回结果之前将结果增加 1,我猜你想找到从 1 而不是 0 开始的索引?如果是这样的话,那就没问题了。


推荐阅读