java - 使用 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 中
解决方案
如果您试图在 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 开始的索引?如果是这样的话,那就没问题了。
推荐阅读
- maven - Nexus 存储库匿名下载:错误还是功能?
- xml - 如何使用 XSLT 替换 XML 节点名称中的字符 - 更改根元素
- reactjs - 反应本机日历标记日期
- java - 在 rest API 中应用 @OrderBy 注释而不是排序
- c++ - 使用输入 C++ 从 .txt 文件中打印 N 行
- list - HASKELL:将列表列表的第一个 x 元素添加到另一个列表中
- java - Java 中的正则表达式电子邮件验证问题
- c++ - 为什么是 std::array
::begin() 自 C++17 以来的 constexpr? - c - C - 显示指针内容。str 和 int 的区别
- postgresql - 如何使用 x IN y,其中 y 是整数列表或查询