HW6.21

本文通过Java程序模拟了豆袋机(Galton Board)的工作原理,用户可以输入豆子的数量和机器槽位的数量,程序随机决定豆子落入哪个槽位,并最终显示每个槽位豆子的数量分布情况及可视化结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 1 import java.util.Scanner;
 2 
 3 public class Solution
 4 {
 5     public static void main(String[] args)
 6     {
 7         Scanner input = new Scanner(System.in);
 8         System.out.print("Enter the number of balls to drop: ");
 9         int numberOfBalls = input.nextInt();
10         System.out.print("Enter the number of slots in the bean machine: ");
11         int numberOfSlots = input.nextInt();
12 
13         input.close();
14 
15         int[] slots = new int[numberOfSlots];
16         int randomNumber;
17         String direction;
18         int count;
19 
20         for(int j = 0; j < numberOfBalls; j++)
21         {
22             count = 0;
23             for(int i = 0; i < numberOfSlots; i++)
24             {    
25                 randomNumber = (int)(Math.random() * 10);
26                 if(randomNumber >= 5)
27                 {
28                     direction = "R";
29                     count++;
30                 }
31                 else
32                     direction = "L";
33                 System.out.print(direction);
34             }
35             slots[count]++;
36             System.out.println();
37         }
38 
39         for(int i = 0; i < numberOfSlots; i++)
40             System.out.print(slots[i] + " ");
41         
42         String[][] outcome = new String[numberOfBalls][numberOfSlots];
43 
44         for(int i = 0; i < numberOfBalls; i++)
45             for(int j = 0; j < numberOfSlots; j++)
46                 outcome[i][j] = " ";
47 
48         for(int i = 0; i < numberOfSlots; i++)
49         {
50             for(int j = numberOfBalls - 1; j > numberOfBalls - slots[i]; j--)
51                 outcome[j][i] = "O";
52         }
53 
54         for(int i = 0; i < numberOfBalls; i++)
55         {
56             for(int j = 0; j < numberOfSlots; j++)
57                 System.out.print(outcome[i][j]);
58             System.out.println();
59         }
60     }
61 }

 

转载于:https://www.cnblogs.com/wood-python/p/5813490.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值