【问题标题】:Official Java excercize solution doesn't work... what I am doing wrong?官方 Java excercize 解决方案不起作用......我做错了什么?
【发布时间】:2020-10-23 04:14:58
【问题描述】:

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
}

【问题讨论】:

  • if (index &gt;= 0) { 中,index 不会在循环的每次迭代中更新,因此它使用您在循环之前计算的值。虽然if (tiplist.contains(tip) == true) { 使用indexOf,但它会在每次循环迭代时重新评估indexOf
  • 欢迎来到 StackOverflow!你能提供一个minimal reproducible example吗?此外,如果您可以编辑以删除“thx”或“atm”等聊天术语,那就太好了:)

标签: java arraylist contains indexof


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    只有知道tip是什么并填写了列表,才能在tipList中找到tip的索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-30
      • 2019-10-19
      • 2011-03-03
      • 2022-07-14
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      相关资源
      最近更新 更多