JAVA Game bean machine

项目要求

输入球的个数和槽的个数,豆豆机中钉子按第几行则有几颗钉子排列,行数为(槽-1)。

打印出每个球的滚动方向,并表现出各个槽中球的分布情况。

 

代码如下

import java.util.Arrays;
import java.util.Scanner;

public class BeanMachine {
	static Scanner input = new Scanner(System.in);

	public static void main(String[] args) {
		System.out.println("Enter the number of balls to drop:");
		int beanNums = input.nextInt();
		System.out.println("Enter the number of slots in the bean machine:");
		int slots = input.nextInt();
		showAnswer(beanNums, slots);
	}

	public static void showAnswer(int beanNums, int slots) {
		int direction;
		int[] Dir = new int[beanNums];
		int[][] Slo = new int[slots][beanNums];
		
		// 一个球一个球往下滚
		for (int i = 0; i < beanNums; ++i) {
			
			// 钉子行数比槽数少1
			for (int j = 0; j < slots - 1; ++j) {

				// direction表示小球向左或向右,取随机数0或1
				direction = (int) (Math.random() * 2);
				
				//当direction为0时,记作向左;为1时,记作向右。Dir[i]为第i个小球滚动过程中有几次向右滚。
				if (direction == 0) {
					System.out.print("L");

				} else {
					System.out.print("R");
					Dir[i]++;
				}
			}
			System.out.println();
		}

		for (int j = 0; j < slots - 1; ++j) {
			
			//Slo[j][count]表示第j个槽由下往上数有多少个球
			int count = beanNums - 1;
			
			for (int i = 0; i < beanNums; ++i) {

				if (Dir[i] == j) {
					Slo[j][count] = 1;
					count--;
				}

			}
		}

		//显示各槽情况
		for (int i = 0; i < beanNums; ++i) {
			
			// 钉子行数比槽数少1
			for (int j = 0; j < slots - 1; ++j) {
				
				if (Slo[j][i] == 1) {
					System.out.print("0");
				} else {
					System.out.print(" ");
				}

			}
			System.out.println();
		}
	}
}


运行结果

Enter the number of balls to drop:
5
Enter the number of slots in the bean machine:
8
LRRRLLR
LLLRLLR
LLRRLRR
RRLRLLL
LLLRRRR
       
       
    0  
    0  
  000  


 

题目来自《JAVA语言程序设计》P230-6.21***

 

 

 

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值