欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

JAVA,

来源: javaer 分享于  点击 12349 次 点评:213

JAVA,


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和count
		k=balls-1;					
		count=slots+1;					//确定二维数组的列数,由题可知最大值即凹槽数是slots+1;
		for (int j=0;j<slots;j++)
		{
			int dir = (int)(Math.random()*2);	 	//产生一个0或1的随机数来决定小球运动的方向,概率均为1/2
			System.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");
			else
				System.out.print(" ");
		}
		System.out.println();
	}
}
}

运行结果:


相关文章

    暂无相关文章
相关栏目:

用户点评