項目要求
輸進球的個數和槽的個數,豆豆機中釘子按第幾行則有幾顆釘子排列,行數為(槽-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) {// 釘子行數比槽數少1for (int j = 0; j < slots - 1; ++j) {// direction表示小球向左或向右,取隨機數0或1direction = (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) {// 釘子行數比槽數少1for (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:5Enter the number of slots in the bean machine:8LRRRLLRLLLRLLRLLRRLRRRRLRLLLLLLRRRR 0 0 000
題目來自《JAVA語言程式設計》P230-6.21***