You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java遍历骰子数组并掷骰,及骰子点数求和实现咨询

Java骰子集合问题解答

1. 遍历数组中的骰子并逐个掷骰

咱们可以通过遍历DieCollection里存储的Die对象数组,对每个骰子调用掷骰方法(比如roll())来实现。假设你的Die类已经有了roll()方法用于生成随机点数,那在DieCollection里可以写一个rollAll()方法来完成批量掷骰:

public class DieCollection {
    private Die[] dice;

    // 构造方法,接收骰子面数数组初始化每个Die
    public DieCollection(int[] sidesArray) {
        dice = new Die[sidesArray.length];
        for (int i = 0; i < sidesArray.length; i++) {
            dice[i] = new Die(sidesArray[i]);
        }
    }

    // 遍历所有骰子并逐个掷骰
    public void rollAll() {
        // 增强for循环遍历数组,简洁直观
        for (Die die : dice) {
            die.roll();
        }

        // 也可以用普通for循环,适合需要索引的场景
        // for (int i = 0; i < dice.length; i++) {
        //     dice[i].roll();
        // }
    }
}

// 假设你的Die类大概是这样的
class Die {
    private int sides;
    private int currentValue;

    public Die(int sides) {
        this.sides = sides;
        this.currentValue = 1; // 初始点数设为1
    }

    public void roll() {
        // 生成1到sides之间的随机数作为当前点数
        currentValue = (int) (Math.random() * sides) + 1;
    }

    public int getCurrentValue() {
        return currentValue;
    }
}

2. 实现已掷骰子点数相加的功能

要计算所有骰子的点数总和,只需要遍历数组里的每个Die,调用它的点数获取方法(比如getCurrentValue()),然后累加所有值就行。咱们可以给DieCollection添加一个getCurrentTotal()方法:

public class DieCollection {
    // 前面的代码不变,新增下面的方法
    public int getCurrentTotal() {
        int total = 0;
        for (Die die : dice) {
            total += die.getCurrentValue();
        }
        return total;
    }
}

这样,当你调用rollAll()掷完所有骰子后,再调用getCurrentTotal()就能得到当前所有骰子的点数总和啦。比如使用的时候:

public class Main {
    public static void main(String[] args) {
        // 比如用户输入要3个骰子,面数分别是6、8、10
        int[] sides = {6, 8, 10};
        DieCollection collection = new DieCollection(sides);
        
        // 掷所有骰子
        collection.rollAll();
        
        // 获取总和
        int total = collection.getCurrentTotal();
        System.out.println("当前所有骰子的点数总和是:" + total);
    }
}

内容的提问来源于stack exchange,提问作者rcv40

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:04:20