官方的Java练习解决方案不起作用...我做错了什么?



atm 我正在做一个Java练习,这是关于将整数与ArrayList的所有元素进行比较。根据这本书的解决方案应该是与"int index = ArrayList.indexOf(comparisonValue(;"和"索引>= 0"。 但对我来说,这是行不通的。我还读到"indexof"只检查ArrayList的第一个位置。但是,如果这是真的,为什么在我的书中将其标记为正确的解决方案?

也许我遇到了错误。这是我的代码,谢谢:)

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
}

你需要在之后使用int index = tiplist.indexOf(tip);tip = 6; //I made it easy to read, normally the number is generated

在您的情况下,值在计算/生成之前分配给index,因此使用默认值可能是您之前设置的。

在你知道提示是什么并填写列表之前,您无法在tipList中找到tipList的索引。

相关内容

最新更新