atm我正在做一个Java摘要,它是关于将一个整数与一个ArrayList的所有元素进行比较。根据本书,解决方案应该是与"int index =ArrayList.indexOf(ComparisonValue)“和"index >= 0”进行比较。但对我来说这不管用。我还读到“索引”只检查ArrayList的第一个位置。但如果这是真的,为什么在我的书中这被标记为正确的解决方案呢?
也许我犯了个错误。这是我的代码thx :)
ArrayList<Integer> tiplist = new ArrayList<Integer>(20);
int des = 0;
int limit = 20;
int tipc = 0;
int index = tiplist.indexOf(tip);
//program loop:
while (des == 0 && tipc < limit) {
tip = 6; //I made it easy to read, normally the number is generated
tipc++; //tip count
if (tipc > 1) { //if it is not the first tip不工作的:
if (index >= 0) {
System.out.println("Nothing new");
}虽然我读到“”也使用了"indexof":
if (tiplist.contains(tip) == true) {
System.out.println("Nothing new");
}最后一行..。
}
tiplist.add(tip);
// -->do something
}发布于 2020-07-02 15:19:05
您需要在int index = tiplist.indexOf(tip);之后使用tip = 6; //I made it easy to read, normally the number is generated
在您的示例中,值是在计算/生成index之前分配给它的,因此使用默认值可能是在前面设置的。
发布于 2020-07-02 14:20:45
在tipList中找不到tip的索引,除非您知道tip是什么,并且已经填写了列表。
https://stackoverflow.com/questions/62698449
复制相似问题