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

Java中如何为ArrayList内的特定数值分配对应奖励分值

6骰子投掷程序奖金规则实现方案

你需要先统计6个骰子掷出点数为2的总数量,再匹配对应奖金规则即可,修改后的代码如下:

首先如果你的类顶部没有导入依赖,需要先补充导入声明:

import java.util.Random;
import javax.swing.JOptionPane;

修改后的业务代码:

public void diceRoll() {
    Random rnd = new Random(); // 随机数生成器
    String resultRoll;

    // 生成1-6的骰子点数,nextInt(6)原生返回0-5范围整数,加1后正好匹配骰子点数
    int n1 = 1 + rnd.nextInt(6); 
    int n2 = 1 + rnd.nextInt(6);
    int n3 = 1 + rnd.nextInt(6);
    int n4 = 1 + rnd.nextInt(6);
    int n5 = 1 + rnd.nextInt(6);
    int n6 = 1 + rnd.nextInt(6);

    resultRoll = n1 + "\n" 
                + n2 + "\n" 
                + n3 + "\n" 
                + n4 + "\n" 
                + n5 + "\n" 
                + n6; // 投掷结果将列出6个骰子各自的点数
    
    // 统计点数为2的出现次数
    int twoCount = 0;
    int[] rolls = new int[] {n1, n2, n3, n4, n5, n6};
    for (int num : rolls) {
        if (num == 2) {
            twoCount++;
        }
    }

    // 匹配奖金规则,兼容所有Java版本的传统switch写法
    int bonus = 0;
    switch (twoCount) {
        case 1:
            bonus = 1;
            break;
        case 2:
            bonus = 5;
            break;
        case 3:
            bonus = 15;
            break;
        default:
            bonus = 0; // 其余情况默认无奖金,可根据后续需求自行调整规则
    }

    // 弹窗展示投掷结果+奖金
    JOptionPane.showMessageDialog(null, "You rolled: \n" + resultRoll + "\n本次获得奖金:" + bonus + " 英镑");
                
    // 可选:控制台打印结果用于调试验证
    System.out.println("点数2出现次数:" + twoCount + ",奖金:" + bonus);
}

public int playerTurn (int playerTurn) {
    return playerTurn + 1;
}

调整说明

  • 简化了随机数生成的冗余写法,逻辑更清晰
  • 去掉了不必要的ArrayList转换步骤,直接用数组遍历统计次数,更适合新手理解
  • 奖金规则可直接在switch代码块里扩展,比如后续要加4个2奖励30英镑的规则,新增case分支即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 05:12:01