Java:掷骰子和输出

标签 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());

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

相关文章:

java - ControlsFX 向导最后一页中的 validator

java - 将混合数组中的值相乘

java - Android recyclerview 向上滚动时加载更多数据

java - JPA/JSP/EJB : How to create tables from entities?

java - 我怎样才能解决一个简单计算器的字符串版本的计算?

java - 将 Account 对象添加到 ArrayList

java - 使用java将多个值添加到列表后仅检索迭代中的最新记录

java - 如何使用 GridBagLayout 维护 jpanel 的尺寸大小?

java - 请求的资源在 Spring MVC 中不可用

java - OOP——每个类的成员变量和方法的数量