Java:滚动骰子并输出

问题描述

| 我尝试滚动骰子,然后在类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());
    ,您正在打印对象,而不是值。采用
System.out.println (\"Dice: \"+ Dices[1]*.value*);
或者您可以向Dice类添加toString()方法。     ,
class Dice{
    int value;
    Dice(){
        value=0;
    }
    void role(){
        int role;
        role = (int)(Math.random()*6+1);
        value=role;
    }

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

}
您需要告诉Java如何打印Dice对象-否则它会使用来自ѭ9的内部表示(对象的类及其哈希代码)     ,您需要在Dice类中添加\“ toString \”方法。     ,您需要重写Dice.toString()     ,您对
println
方法的论点是
\"Dice: \"+ Dices[1]
+
运算符可以将String与任意对象连接在一起,这可以通过先将对象转换为String来实现。由于存在this9ѭ实例方法,该方法可以返回任何对象的字符串表示形式,因此可以执行此操作。 这就是将
Dice[1]
转换为字符串常量的方式(您看到的是从
Object
继承的ѭ15implementation的默认实现)。 因此,您有两种方法可以解决此问题: 在您的
Dice
班级上改写
public String toString()
。请注意,这将是类实例的默认\“字符串表示\\”,它们以文本形式输出,因此请选择在一般情况下有意义的选项。要么: 将“ 3”引用的值显式传递到println语句中。
println(\"Dice: \" + Dices[1].value)
之类的东西。