问题描述
豆机,也称为梅花瓶或者高尔顿瓶,它是一个用来做统计实验的设备,以英国科学家弗兰克斯·高尔顿的名字来命名。它是一个三角形状的均匀放置钉子的直立板子,如下图所示:
实现思想
根据随机路径中R的个数以判断小球落入第几个槽,统计每个槽的小球个数。
实现提示
创建一个数组来存取槽中小球的个数。
注意随机性为50%。
代码
高尔顿瓶类:
public class BeanMachine {
private int initialBalls;
private int initialSlots;
private int[] slots;
public BeanMachine() {
this(1,5);
}
public BeanMachine(int i,int n) {
initialBalls = i;
initialSlots = n;
slots = new int[n];
}
public static void menu() {
java.util.Scanner input = new java.util.Scanner(System.in);
int balls;
int slots;
System.out.print("Enter the number of balls to drop: ");
balls = input.nextInt();
System.out.print("Enter the number of slots in the bean machine: ");
slots = input.nextInt();
BeanMachine mine = new BeanMachine(balls,slots);
mine.play();
}
public void play() {
for(int i = 1;i <= initialBalls;i++) {
printPath();
}
System.out.println("");
printChart();
}
public void printPath() {
int judge;
int numberOfR = 0;
for(int i = 0;i < initialSlots-1;i++) {
judge = (int)(Math.random()*2);
if(judge == 0)
System.out.print("L");
if(judge == 1) {
numberOfR++;
System.out.print("R");
}
}
System.out.println("");
slots[numberOfR]++;
}
public void printChart() {
int max = getMax();
for(int i = 0;i < max;i++) {
for(int j = 0;j < initialSlots;j++) {
if(slots[j] >= max - i)
System.out.print("0");
else
System.out.print(" ");
}
System.out.println("");
}
}
public int getMax() {
int max = slots[0];
for(int i = 0;i < slots.length; i++) {
if(slots[i] > max) max = slots[i];
}
return max;
}
}
主类:
public class test_BeanMachine {
public static void main(String[] args) {
BeanMachine.menu();
}
}
debug
其中代码构造函数中:
public BeanMachine(int i,int n) {
initialBalls = i;
initialSlots = n;
int [] slots = new int[n];
}
int [] slots = new int[n]
重新创建了一个与数据域slots数组同名的int数组,将数据域覆盖,导致slots未分配内存空间,导致后续出现逻辑错误!!!