1. 程式人生 > >***6.21-豆機 梅花瓶 高爾頓瓶

***6.21-豆機 梅花瓶 高爾頓瓶

問題及程式碼:
/*   
*Copyright (c)2015,煙臺大學計算機與控制工程學院   
*All rights reserved.   
*檔名稱:Slots.java   
*作    者:單昕昕   
*完成日期:2015年10月10日   
*版 本 號:v1.0   
*   
*問題描述:遊戲:模擬豆機/梅花瓶/高爾頓瓶。
*程式輸入:球的個數、機器的槽數。
*程式輸出:球的路徑、槽中球的儲備情況。  
*/ 
import java.util.*;
import java.util.Scanner;
public class Test
{
    public static void main(String[] args)
    {
        int ball,slot,n,i,j,t,cnt;
        Scanner input=new Scanner(System.in);
        System.out.print("Enter the number of balls to drop:");
        ball =input.nextInt();//輸入球的個數
        System.out.print("Enter the number of slots to drop:");
        slot =input.nextInt();//輸入槽的個數
        int[]slots=new int[slot];//槽中球的個數
        String []dirction= {"L","R"};//球的方向
        Random random = new Random();
        for(i=0; i<ball; ++i)
        {
            cnt=0;
            for(j=0; j<slot; ++j)
            {
                t=Math.abs(random.nextInt())%2;//產生隨機方向
                if(t==1)
                    ++cnt;//計算R的個數
                System.out.print(dirction[t]);
            }
            ++slots[--cnt];//球落入槽的位置
            System.out.println();
        }
        int max=slots[0];//輸出槽中球的儲備情況
        for(i=0; i<ball; ++i)
            if(slots[i]>max)
                max=slots[i];
        for(i=0; i<max; ++i)//按行判斷輸出
        {
            for(j=0; j<ball; ++j)
            {
                if(slots[j]>=(max-i))//自上而下依次判斷各個槽,輸出槽中球個數的圖
                    System.out.print("0");//球用0表示
            }
            System.out.println();
        }
    }
}



執行結果:



知識點總結:
隨機數、一維陣列

學習心得:

(⊙v⊙)嗯有了書上的提示好簡單。。