Java黑皮书课后题第7章:**7.24(仿真:优惠券收集问题)优惠券收集问题是一个经典的统计问题。编写程序,模拟要得到四张不同花色的牌所需要的选取次数,然后显示选中的四张牌
生活随笔
收集整理的這篇文章主要介紹了
Java黑皮书课后题第7章:**7.24(仿真:优惠券收集问题)优惠券收集问题是一个经典的统计问题。编写程序,模拟要得到四张不同花色的牌所需要的选取次数,然后显示选中的四张牌
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
**7.24(仿真:優(yōu)惠券收集問題)優(yōu)惠券收集問題是一個(gè)經(jīng)典的統(tǒng)計(jì)問題。編寫程序,模擬要得到四張不同花色的牌所需要的選取次數(shù),然后顯示選中的四張牌
- 題目
- 題目描述與運(yùn)行示例
- 破題:花色與數(shù)字
- 代碼
題目
題目描述與運(yùn)行示例
**7.24(仿真:優(yōu)惠券收集問題)優(yōu)惠券收集問題是一個(gè)經(jīng)典的統(tǒng)計(jì)問題……
從一副打亂的52張牌中重復(fù)選牌,直到每種花色都選過一張,需要選多少次
編寫程序,模擬要得到四張不同花色的牌所需要的選取次數(shù),然后顯示選中的四張牌
運(yùn)行示例:
破題:花色與數(shù)字
代碼
public class Test7_24 {public static void main(String[] args) {//1. 創(chuàng)建4個(gè)boolean值表4種花色是否出現(xiàn)賦值為false,boolean bool1 = false, bool2 = false, bool3 = false, bool4 = false;// 另有2個(gè)int值計(jì)數(shù)變量計(jì)算選取次數(shù)、數(shù)組下標(biāo)并賦值為0,1個(gè)長度為4的int型數(shù)組int count_pick = 0, count_index = 0, temp = 0;int[] list = new int[4];//2. 通過循環(huán)不斷抽牌(int)(Math.random()*52+1)(抽牌的前提:四個(gè)boolean值不都為true),while (!(bool1 && bool2 && bool3 && bool4)) {temp = (int)(Math.random()*52+1);//選取次數(shù)計(jì)數(shù)變量自增1++count_pick;//求得值對(duì)應(yīng)花色的boolean值如果為false,則將這個(gè)值存放在數(shù)組中,數(shù)組下標(biāo)計(jì)數(shù)變量自增1并改boolean為trueif (temp % 4 == 0 && !bool1){list[count_index] = temp;++count_index;bool1 = true;}else if (temp % 4 == 1 && !bool2){list[count_index] = temp;++count_index;bool2 = true;}else if (temp % 4 == 2 && !bool3){list[count_index] = temp;++count_index;bool3 = true;}else if (temp % 4 == 3 && !bool4){list[count_index] = temp;++count_index;bool4 = true;}}//3. 遍歷數(shù)組,每個(gè)元素%4對(duì)應(yīng)不同花色、%13對(duì)應(yīng)不同值并輸出for (int i = 0 ; i < 4 ; i++){int a = list[i] % 13;int b = list[i] % 4;// 轉(zhuǎn)為數(shù)值并輸出switch (a) {case 0 -> System.out.print("K");case 1 -> System.out.print("A");case 2 -> System.out.print("2");case 3 -> System.out.print("3");case 4 -> System.out.print("4");case 5 -> System.out.print("5");case 6 -> System.out.print("6");case 7 -> System.out.print("7");case 8 -> System.out.print("8");case 9 -> System.out.print("9");case 10 -> System.out.print("10");case 11 -> System.out.print("J");case 12 -> System.out.print("Q");}// 輸出" of "System.out.print(" of ");// 轉(zhuǎn)為花色并輸出switch (b) {case 0 -> System.out.println("Spades");case 1 -> System.out.println("Clubs");case 2 -> System.out.println("Hearts");case 3 -> System.out.println("Diamonds");}}//4. 輸出選取次數(shù)System.out.println("Number of picks: " + count_pick);} }總結(jié)
以上是生活随笔為你收集整理的Java黑皮书课后题第7章:**7.24(仿真:优惠券收集问题)优惠券收集问题是一个经典的统计问题。编写程序,模拟要得到四张不同花色的牌所需要的选取次数,然后显示选中的四张牌的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java黑皮书课后题第7章:**7.23
- 下一篇: Java黑皮书课后题第7章:7.26(完