gpt4 book ai didi

Java:掷骰子和输出

转载 作者:行者123 更新时间:2023-12-02 00:41:56 24 4
gpt4 key购买 nike

我尝试掷骰子,然后当我在 Player 类中调用 slaTarningar() 时系统打印 1 个骰子,

class Player{
int armees = 0;
int diceAmount = 0;
Dice Dices[];
Player(String playerType){
armees = 10;
diceAmount = ("A".equals(playerType)) ? 3 : 2;
Dices= new Dice[diceAmount];
for(int i=0;i<Dices.length;i++){
Dices[i]=new Dice();
}
}
void slaTarningar(){
for(int i=0;i<Dices.length;i++){
Dices[i].role();
}
System.out.println ("Dice: "+ Dices[1]);
}
void visaTarningar(){
String allDices="";

for(int i=0;i<Dices.length;i++){
allDices += ", " + Dices[i];
}
}
}
class Dice{
int value;
Dice(){
value=0;
}
void role(){
int role;
role = (int)(Math.random()*6+1);
value=role;
}
}

我得到的只是我的项目名称,还有一些奇怪的东西:

Dice: javaapplication9.Dice@9304b1 

这里出了什么问题?

最佳答案

您需要向 Dice 添加一个 toString 方法:

class Dice{
int value;
Dice(){
value=0;
}
void role(){
int role;
role = (int)(Math.random()*6+1);
value=role;
}

public String toString() {
return "" + value + "";
}
}

或者添加一个getValue方法:

class Dice{
int value;
Dice(){
value=0;
}
void role(){
int role;
role = (int)(Math.random()*6+1);
value=role;
}

public int getValue() {
return value;
}
}

//.. in other class:
System.out.println ("Dice: "+ Dices[1].getValue());

关于Java:掷骰子和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6127237/

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