我尝试掷骰子,然后当我在 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/