gpt4 book ai didi

java - 我可以在将对象与另一个数组进行比较时更改对象的一个​​值吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:05:23 25 4
gpt4 key购买 nike

我有一个对象,它有一个名称,String [] 还有另一个 String 数组,它只存储对象的名称(第一个参数),它在 main 中。

import java.util.*;
class Dice{
public String [] side;
public String name;

public Dice (String n, String ... a){
name = n;
side = a;

}

//Setter and Getter name
public String getName(){
return name;
}
public void setName(String n){
name = n;
}
}

对象参数在主类中设置。

Dice easy = new Dice("Green:","Brain","Brain","Brain","Foot Print","Foot Print","Shotgun");

字符串数组只存储名称Easy:

我试图通过将两个数组传递给 main 中的方法来比较它们。

//Removeing the 3 dice which were picked form the cup of the current player
public static Dice [] cup(Dice [] a , String [] b){
Dice [] currentCup = new Dice[a.length];


for (int i = 0; i < b.length; i++) {
if (b[i] == a[i].getName()) {
currentCup[i].setName("");
}
}

return currentCup;
}

如果对象的名称等于 String 数组中的名称,则对象名称应等于且为空 String("")。

我遇到了一个错误

线程“main”中的异常 java.lang.NullPointerException

我知道在这里使用 ArrayList 更好,因为我可以 .remove(i, elem)。但我不知道如何将 ArrayList 传递给构造函数。

此外,这只是我自己使用数组的纯粹练习。

结果应该是,如果 Dice [].getName() 等于 easy,则该 Dice 对象的名称应该是一个空字符串“”。

最佳答案

I understand that an ArrayList is much better to use here as I can just .remove(i, elem). But I do not know how to pass an ArrayList into a constructor.

public Dice (String n, List<String> sideList){
name = n;
side = sideList.toArray(new String[sideList.size()]);

}

此外,您没有对以下数组执行任何操作。

Dice [] currentCup = new Dice[a.length];

我强烈建议您自己试运行代码。看起来你的代码并没有做你真正想做的事情。 :)

关于java - 我可以在将对象与另一个数组进行比较时更改对象的一个​​值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57908755/

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