JAVA

来源:互联网 发布:马东为什么离婚知乎 编辑:程序博客网 时间:2024/09/21 11:16
import java.util.Scanner;public class HelloWorld{public static void main(String[] args){char[] Dirs={'L','R'};              //定义数组确定方向int[][]showAnswer=new int[10][10];Scanner input = new Scanner(System.in);System.out.print("Enter the number of balls to drop:");int balls = input.nextInt();//balls为球的个数System.out.print("Enter the number of slots in the bean machine:");int slots = input.nextInt();//slots为钉子数System.out.println();int k,count;for (int i=0;i<balls;i++){                                  //每一个小球重置一次k和countk=balls-1;count=slots+1;//确定二维数组的列数,由题可知最大值即凹槽数是slots+1;for (int j=0;j<slots;j++){int dir = (int)(Math.random()*2); //产生一个0或1的随机数来决定小球运动的方向,概率均为1/2System.out.print(Dirs[dir]);//输出小球运动的方向if (dir==0)//小球向左则count--count--;else//向右则count++count++;}System.out.println();while(showAnswer[k][count/2]==1)                   //当底层已经有小球时则向上挪一层{k--;}showAnswer[k][count/2]=1;//确定该位置为1}for (int i=0;i<balls;i++)                      //当showAnswer[i][j]=1时输出0{for (int j=0;j<slots+1;j++){if (showAnswer[i][j]==1)System.out.print("O");elseSystem.out.print(" ");}System.out.println();}}}

运行结果:


1 0
原创粉丝点击