gpt4 book ai didi

Java arraylist所有项目都是相同的

转载 作者:行者123 更新时间:2023-11-30 06:50:57 25 4
gpt4 key购买 nike

为什么列表中的所有卡片都相同?我尝试了hand.add(i,card);但输出仍然相同。

Main.java

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Main {

public static void main(String[] args) {
List<Card> hand = new ArrayList();
Card card = new Card((short) 7,"red");
int b = 0;
Random rn = new Random();
for (int i=0;i<7;i++){
card.setValue((short) (rn.nextInt((14 - 7) + 1) + 7));
b = rn.nextInt(4);
String[] colors = {"green","red","gold","brown"};
card.setColor(colors[b]);
System.out.println("Adding card to hand: " + card.getColor() + card.getValue() + " to: " +i);
hand.add(card);
}
System.out.println("Your cards: ");
for (Card k: hand) {
System.out.println(k.show());
}


}
}

卡片.java

public class Card {
public short getValue() {
return value;
}

public void setValue(short value) {
this.value = value;
}

short value;

public String getColor() {
return color;
}

public void setColor(String farba) {
this.color = farba;
}

String color;

public Card(short value, String color) {
this.value = value;
this.color = color;
}

public String show(){
return color + value;
}
}

输出:

/usr/lib/jvm/java-1.8.0-openjdk-amd64/bin/java
Adding card to hand: red13 to: 0
Adding card to hand: green10 to: 1
Adding card to hand: gold8 to: 2
Adding card to hand: brown10 to: 3
Adding card to hand: gold10 to: 4
Adding card to hand: gold8 to: 5
Adding card to hand: gold7 to: 6
Your cards:
gold7
gold7
gold7
gold7
gold7
gold7
gold7

Lorem ipsum dolor sat amet,consectetur adipiscing elit。 Aenean nisl.Curabitur ac arcu ornare、aliquet eros eu、pretium Massa。

最佳答案

您对列表中的所有项目使用相同的 Card 对象,但您需要不同的对象(每个 Card 对象都拥有自己的颜色和值),因此您必须在 for 循环内创建new Card,如下所示:

    int b = 0;
Random rn = new Random();
for (int i=0;i<7;i++){

b = rn.nextInt(4);
String[] colors = {"green","red","gold","brown"};

Card card = new Card((short) (rn.nextInt((14 - 7) + 1) + 7),colors[b]);

System.out.println("Adding card to hand: " +
card.getColor() + card.getValue() + " to: " +i);

hand.add(card);
}

关于Java arraylist所有项目都是相同的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40691196/

25 4 0