Java入门实验求助:用do-while与随机数模拟掷骰子统计对子次数
Fixing Your Dice Roll Simulation Code
Let’s walk through the issues in your code and get it working properly for simulating 10,000 dice rolls and counting matching pairs:
Key Issues in Your Original Code
- Incorrect Random Number Generation: Your current code
(int)(Math.random()*6)-1produces numbers from-1to4—not the 1-6 range we need for dice. Plus, the task specifies using aRandomobject instead ofMath.random(). - Broken Loop Control: The loop condition
x > 10000will never trigger (sincexstarts at 0), and you never incrementxinside the loop, so even if the condition was right, it would run infinitely. - Unreachable Pair Checks: Since your dice values are wrong, the checks for 1-6 pairs will never hit correctly.
Corrected Code
import java.util.Random; public class DiceRoll { public static void main(String []args){ int rollCount = 0; int counter1 = 0; int counter2 = 0; int counter3 = 0; int counter4 = 0; int counter5 = 0; int counter6 = 0; // Initialize Random object as required Random random = new Random(); do { // Generate 1-6 using Random's nextInt method (nextInt(6) gives 0-5, add 1 to shift to 1-6) int dice1 = random.nextInt(6) + 1; int dice2 = random.nextInt(6) + 1; if (dice1 == dice2) { // Use switch for cleaner pair checking (if statements work too, switch is more concise) switch(dice1) { case 1: counter1++; break; case 2: counter2++; break; case 3: counter3++; break; case 4: counter4++; break; case 5: counter5++; break; case 6: counter6++; break; } } // Increment our roll counter each iteration rollCount++; } while (rollCount < 10000); // Run until we've done 10,000 rolls System.out.println("Results of 10,000 dice roll simulations:"); System.out.println("1-1 pairs: " + counter1); System.out.println("2-2 pairs: " + counter2); System.out.println("3-3 pairs: " + counter3); System.out.println("4-4 pairs: " + counter4); System.out.println("5-5 pairs: " + counter5); System.out.println("6-6 pairs: " + counter6); } }
What Changed?
- Added
RandomObject: We useRandom random = new Random()andrandom.nextInt(6) + 1to generate proper 1-6 values—this aligns with the task's requirement. - Fixed Loop Logic: Renamed
xtorollCountfor clarity, increment it each loop, and userollCount < 10000as the condition to run exactly 10,000 times. - Cleaned Up Pair Checking: Switched to a
switchstatement for more readable pair counting (your original if statements would work too if the dice values were fixed, but switch is neater here). - Fixed Dice Value Range:
random.nextInt(6)gives 0-5, adding 1 shifts it to the correct 1-6 range for standard dice.
When you run this, you’ll see each pair count is roughly around 1/36 of 10,000 (about 277) since each pair has a 1/36 probability of occurring—this makes sense statistically!
内容的提问来源于stack exchange,提问作者Luke Auslender
相关产品推荐
相关产品推荐

