Java骰子模拟:实现指定点数匹配及尝试次数统计功能求助
解决骰子掷点循环问题的方案
嘿,我来帮你搞定这个骰子程序的问题!你想要的是循环掷骰子直到命中目标点数,每次输出尝试次数和结果,最后统计总次数对吧?你的现有代码已经完成了输入和单次掷骰子的部分,差的就是循环逻辑,我来给你理顺清楚。
核心思路
我们需要重复掷骰子的动作,直到掷出用户指定的点数。因为不知道要循环多少次,用do-while循环会更贴合场景(它能保证至少执行一次掷骰子的操作,符合实际需求),当然用for循环也能实现,我两种都给你演示下。
完整代码实现(推荐do-while版本)
import java.util.Scanner; public class DiceGame { public static void main(String[] args) { Scanner s = new Scanner(System.in); // 询问用户目标点数 System.out.println("你想要多少点的骰子?"); int targetDots = s.nextInt(); // 可选:添加输入验证,确保点数在1-6之间 if (targetDots < 1 || targetDots > 6) { System.out.println("请输入1到6之间的有效点数哦!"); s.close(); return; } int attempts = 0; int currentDots; // do-while循环:先执行一次掷骰子,再判断是否命中 do { attempts++; currentDots = (int) (6 * Math.random()) + 1; System.out.println("尝试" + attempts + ":" + currentDots); } while (currentDots != targetDots); // 循环结束后输出结果 System.out.println("经过" + attempts + "次尝试,你找到了" + targetDots + "点"); s.close(); } }
代码解释
- 输入处理:用
Scanner获取用户输入的目标点数,还加了简单的输入验证,避免用户输入1-6以外的无效值。 - 循环逻辑:
do-while会先执行一次掷骰子操作,每次尝试次数attempts加1,然后输出当前结果;如果没命中目标点数,就继续循环,直到掷出目标点数才停止。 - 结果输出:循环结束后,统计总尝试次数并打印最终提示。
用for循环实现的版本
如果你坚持想用for循环,也可以写成无限循环+内部判断跳出的形式:
import java.util.Scanner; public class DiceGameForLoop { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("你想要多少点的骰子?"); int targetDots = s.nextInt(); if (targetDots < 1 || targetDots > 6) { System.out.println("请输入1到6之间的有效点数哦!"); s.close(); return; } int attempts = 0; // 无限for循环,通过break跳出 for (; ; ) { attempts++; int currentDots = (int) (6 * Math.random()) + 1; System.out.println("尝试" + attempts + ":" + currentDots); if (currentDots == targetDots) { break; // 命中目标,跳出循环 } } System.out.println("经过" + attempts + "次尝试,你找到了" + targetDots + "点"); s.close(); } }
两种写法都能实现你要的效果,do-while版本逻辑更直观,更符合“至少掷一次骰子”的场景,推荐你用这个哦!
内容的提问来源于stack exchange,提问作者florian de wulf
相关产品推荐
相关产品推荐

