gpt4 book ai didi

java - 将数组列表的元素复制到另一个数组列表

转载 作者:行者123 更新时间:2023-12-01 17:37:09 24 4
gpt4 key购买 nike

我写了这样一个简单的代码:

  • 我在类的构造函数中编写了这一行:List element = new ArrayList();

  • 我有一个名为 cost 的变量,其类型为 int

  • 一个方法将返回三个具有不同对象的列表:listOne、listTwo、listThree

  • 在另一个方法中,我在下面编写了代码,该方法将使用在上面的方法中创建的那些列表。对于上面的三个列表,该方法将被调用三次。每个列表的每个调用。

    // begining of the method:
    int cost = 0;

    if(cost==0){
    element = listOne;
    cost = 3;
    }
    if(cost<4){
    element = listtwo;
    cost = 6;
    }
    // end

    System.out.println(element.toString());

不幸的是,它不会打印 listTwo ,而是打印 listThree (如果我们有 4 个或更多列表,它将打印最后一个)!

if-else条件有问题吗?

谢谢

编辑:这是我的主要代码,但其条件类似于上面的代码:下面代码中的auxiliaryList分别是listOnelist TwolistThree

cost = 0;

public void method {


System.out.println(element.toString());//number one
if (cost== 0) {


element = auxiliaryList;
cost = 3;

}
else if( cost<4){

element =auxiliaryList;
cost = 6;
}

}
return;

}

}

//number one 声明的行还告诉我,在进入 if/else 条件之前,元素列表将设置为方法中的当前列表。

最佳答案

Is there any problem with if-else condition.

是的 - 问题是您没有使用 if/else,您只是使用了两个 if 语句。

将第二个 if 更改为使用 else 就可以了:

  if (cost == 0) {
element = listOne;
cost = 3;
} else if (cost < 4) {
element = listtwo;
cost = 6;
}

问题是,如果cost为0,它将进入第一个 block ,将cost设置为3,然后进入第二个 block ,因为 3 小于 4。没有“else”来阻止这种情况发生 - 两个 if block 是完全独立的。

关于java - 将数组列表的元素复制到另一个数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5151498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com