2015-02-06 29 views
0

我想創建一個程序,要求用戶輸入要滾動的6個雙面骰子的數量,然後輸入他們想要運行多少個滾動(試驗)。在代碼結束時,它應該向用戶顯示每個可能的數字有多少,並且是否存在條紋(如果有的話應該說明條紋是什麼以及它開始的滾動編號。)在Java中使用數組的骰子滾筒模擬器

保持簡單到目前爲止,我的程序應該只詢問用兩個6面骰子運行多少次試驗並顯示上面列出的顯示器

問題是顯示器沒有顯示百分比,因爲我的數學應該允許以及何時它來到連勝我不知道如何說明哪些審判開始在哪些數字是在連勝....任何幫助將不勝感激。

import java.util.*; 

公共類RollThoseDice {

public static void main(String[] args) { 
    //start of method 

    //variables needed for program 
    int total; 
    int newStreak = 1; 
    int streak = 1; 
    int totalIs2 = 0; 
    int totalIs3 = 0; 
    int totalIs4 = 0; 
    int totalIs5 = 0; 
    int totalIs6 = 0; 
    int totalIs7 = 0; 
    int totalIs8 = 0; 
    int totalIs9 = 0; 
    int totalIs10 = 0; 
    int totalIs11 = 0; 
    int totalIs12 = 0; 
    double twoPercent = 0; 
    double threePercent = 0; 
    double fourPercent = 0; 
    double fivePercent = 0; 
    double sixPercent = 0; 
    double sevenPercent = 0; 
    double eightPercent = 0; 
    double ninePercent = 0; 
    double tenPercent = 0; 
    double elevenPercent = 0; 
    double twelvePercent = 0; 

    //intro to program and purpose 
    System.out.println("Today we are going to generate 2 random dice and tally the results of their random combined rolls"); 
    System.out.println("At the bottom of the results, the longest streak will also be listed"); 

    //variable for while loop 
    boolean validInput = true; 
    //declaration of scanner before try/catch 
    Scanner userInput = new Scanner(System.in); 

    //test for valid input 
    while (validInput){ 
     try { 
      System.out.print(" \n" + "Please enter the number of trials you would like to be performed:"); 
      int numberOfRolls = Integer.parseInt(userInput.nextLine()); 

      //Stop from calling for anything else 
      userInput.close(); 

      //declaring of variables for die 1 and die 2 
      int die1[] = new int[numberOfRolls]; 
      int die2[] = new int[numberOfRolls]; 


      //create an array for each die roll so that they can each be saved for recalling streak 
      int[] array = new int[numberOfRolls]; 
      for (int i=1; i<array.length; i++) { 
       die1[i] = (int) ((Math.random() * 6) + 1); 
       die2[i] = (int) ((Math.random() * 6) + 1); 
       total = die1[i] + die2[i]; 

       //streak checker 
       int lastTotal = die1[i-1] + die2[i-1];   
       if (lastTotal == total) { 
        streak++; 
        if (streak > newStreak) { 
         newStreak = streak; 
        } 
       } else { 
        streak = 1; 
       } 

       //count total of each numbered possibility rolled 
       if (total == 2) { 
        totalIs2++; 
       } 
       if (total == 3) { 
        totalIs3++; 
       } 
       if (total == 4) { 
        totalIs4++; 
       } 
       if (total == 5) { 
        totalIs5++; 
       } 
       if (total == 6) { 
        totalIs6++; 
       } 
       if (total == 7) { 
        totalIs7++; 
       } 
       if (total == 8) { 
        totalIs8++; 
       } 
       if (total == 9) { 
        totalIs9++; 
       } 
       if (total == 10) { 
        totalIs10++; 
       } 
       if (total == 11) { 
        totalIs11++; 
       } 
       if (total == 12) { 
        totalIs12++; 

        //calculate percent of each number rolled 
        twoPercent = (totalIs2/numberOfRolls); 
        threePercent = (totalIs3/numberOfRolls); 
        fourPercent = (totalIs4/numberOfRolls); 
        fivePercent = (totalIs5/numberOfRolls); 
        sixPercent = (totalIs6/numberOfRolls); 
        sevenPercent = (totalIs7/numberOfRolls); 
        eightPercent = (totalIs8/numberOfRolls); 
        ninePercent = (totalIs9/numberOfRolls); 
        tenPercent = (totalIs10/numberOfRolls); 
        elevenPercent = (totalIs11/numberOfRolls); 
        twelvePercent = (totalIs12/numberOfRolls); 
       } 
      } 

      //results 
      System.out.println("\n" + "Total Results:"); 
      System.out.println("\n" + "Total 2 happened " + totalIs2 + " times which is " + twoPercent + "%"); 
      System.out.println("Total 3 happened " + totalIs3 + " times which is " + threePercent + "%"); 
      System.out.println("Total 4 happened " + totalIs4 + " times which is " + fourPercent + "%"); 
      System.out.println("Total 5 happened " + totalIs5 + " times which is " + fivePercent + "%"); 
      System.out.println("Total 6 happened " + totalIs6 + " times which is " + sixPercent + "%"); 
      System.out.println("Total 7 happened " + totalIs7 + " times which is " + sevenPercent + "%"); 
      System.out.println("Total 8 happened " + totalIs8 + " times which is " + eightPercent + "%"); 
      System.out.println("Total 9 happened " + totalIs9 + " times which is " + ninePercent + "%"); 
      System.out.println("Total 10 happened " + totalIs10 + " times which is " + tenPercent + "%"); 
      System.out.println("Total 11 happened " + totalIs11 + " times which is " + elevenPercent + "%"); 
      System.out.println("Total 12 happened " + totalIs12 + " times which is " + twelvePercent + "%"); 
      System.out.println("The longest run was a run of " + newStreak + " *number that was on a streak*" + " that began at roll" + "*where it started*"); 

      //stop the loop 
      validInput = false; 
     } 

     //catch exception and call for new input 
     catch(Exception e){ 
      System.out.println("\n" + "Your input was not a number. Please try again: "); 
     } 
    } 
} 
+0

爲什麼不是你的for循環從0開始? 當你有很長的這樣的IF語句時,你應該把這兩個die的總和存儲在'array'數組中 – 2015-02-06 09:23:28

+0

,你應該考慮使用switch語句來清晰。 – 2015-02-06 09:51:06

回答

0

你應該只//results之前將您的//calculate percent of each number rolled計算。注意你把它放在if (total == 12)裏面。它實際上應該是percents[i] = (total[i] * 100/numberOfRolls);

你會寫類似下一次:

int totalIs2 = 0; 
int totalIs3 = 0; 
... 

您應該使用數組

和你可以寫一個for循環,而不是線性重複的代碼


即您可以替換:

//calculate percent of each number rolled 
twoPercent = (totalIs2/numberOfRolls); 
... 

System.out.println("\n" + "Total 2 happened " + totalIs2 + " times which is " + twoPercent + "%"); 
... 

for (int i = 2; i < totalCount.length; i++) { 
    double percent = totalCount[i] * 100/ numberOfRolls; 
    System.out.println("\n" + "Total " + i + " happened " + totalCount[i] + " times which is " + percent + "%"); 
} 

這裏的整個程序:

public class RollThoseDices { 
    private int lastTotal; 
    private int streak; 
    private int longestStreak; 
    private int startOfTheLongestStreak; 

    private int[] totalCount = new int[13]; 

    RollThoseDices(int numberOfRolls) { 
     run(numberOfRolls); 
    } 

    public void run(int numberOfRolls) { 
     for (int i=0; i<numberOfRolls; i++) { 
      int die1 = (int) ((Math.random() * 6) + 1); 
      int die2 = (int) ((Math.random() * 6) + 1); 
      int total = die1 + die2; 
      totalCount[total]++; 

      if (lastTotal == total) { 
       streak++; 
       if (streak > longestStreak) { 
        longestStreak = streak; 
        startOfTheLongestStreak = i - longestStreak; 
       } 
      } else { 
       streak = 1; 
      } 
      lastTotal = total; 
     } 
    } 

    private static int readInt(Scanner scanner) { 
     System.out.print(" \n" + "Please enter the number of trials you would like to be performed:"); 
     while (!scanner.hasNextInt()) { 
      scanner.next(); 
      System.out.println("\n" + "Your input was not a number. Please try again: "); 
     } 
     return scanner.nextInt(); 
    } 

    public static void main(String[] args) { 
     //intro to program and purpose 
     System.out.println("Today we are going to generate 2 random dice and tally the results of their random combined rolls"); 
     System.out.println("At the bottom of the results, the longest streak will also be listed"); 

     // read number of rolls 
     int numberOfRolls = 0; 
     try(Scanner userInput = new Scanner(System.in)) { 
      numberOfRolls = readInt(userInput); 
     } 

     RollThoseDices results = new RollThoseDices(numberOfRolls); 

     //results 
     System.out.println("\n" + "Total Results:"); 
     System.out.println("The longest run was a run of " + results.longestStreak + " that began at roll " + results.startOfTheLongestStreak); 
     for (int i = 2; i < results.totalCount.length; i++) { 
      double percent = (results.totalCount[i] * 100.0)/numberOfRolls; 
      System.out.println("\n" + "Total " + i + " happened " + results.totalCount[i] + " times which is " + percent + "%"); 
     } 
    } 
} 
0

如lifus在第一個答案所提到的,使用數組。此外,條紋以及從哪個試驗開始可以輕鬆存儲。將起始位置存儲爲 start = current_trial_no - current_longest_streak。這意味着您的變量分配進入您存儲最長條紋值的部分。

import java.util.*; 
import java.lang.*; 
import java.io.*; 
import java.text.DecimalFormat; 

class Ideone 
{ 
    public static void main (String[] args) throws java.lang.Exception 
    { 
     Scanner cin = new Scanner(System.in); 
     boolean run = true ; 
     int[] sum = new int[13] ; 
     float[] percent = new float[13]; 
     int streak = 0, streakValue = 0, currentStreak = 0, streakStart = 0, trials = 0 ; 
     int dice1 = 0, dice2 = 0 ; 
     for(int i = 0; i < sum.length; ++i) 
     { 
      sum[i] = 0 ; 
      percent[i] = 0.0f; 
     } 
     do 
     { 
      trials = cin.nextInt(); 
      int prevSum = 0 ; 

      for(int t = 0; t < trials; ++t) 
      { 
       dice1 = (int) ((Math.random() * 6) + 1); 
       dice2 = (int) ((Math.random() * 6) + 1); 
       sum[dice1 + dice2]++ ; 
       if((dice1 + dice2) == prevSum) 
       { 
        ++currentStreak ; 
        streakValue = prevSum ; 
        if(currentStreak > streak) 
        { 
         streak = currentStreak ; 
         streakStart = t - streak ; 
        } 
       } 
       else { 
        currentStreak = 1 ; 
       } 
       prevSum = dice1 + dice2 ; 
      } 

      System.out.println("Continue ? (y/n) : "); 
      run = cin.nextLine().equals("y"); 
     } while(run); 

     DecimalFormat df = new DecimalFormat("###.##"); 

     // Start from 2 - the minimum sum possible. 
     for(int i = 2; i < 13; ++i) 
     { 
      percent[i] = (float)sum[i]/(float)trials * 100.0f ; 
      System.out.println("The sum " + i + " has occurred " + df.format(percent[i]) + "% of times"); 
     } 
     System.out.println("Longest streak of " + streakValue + " has occurred for " + streak + " times"); 
     System.out.println("It started at : " + streakStart); 
    } 

} 

請注意環內的if條件的內部。 Here是相同的工作版本。

+0

我真的很感謝大家的幫助(甚至保存了最後的代碼作爲以後的繼續選項的參考)。感謝你們!這基本上是我目前所在的位置,但我可能會在未來再調整一下。再次感謝! – Jdub 2015-02-06 19:33:12

+0

我似乎無法縮進,現在就給我的代碼...對不起....(我是全新的...對不起) – Jdub 2015-02-06 19:36:20

+0

4個空格而不是一個製表符縮進。 – 2015-02-06 21:28:04

0

看起來像你已經給出了使用數組的立即建議。正如其他人已經證明,這顯着縮短了輸入代碼的代碼行和重複性。 我要強調的另一件事是編程時嘗試更抽象地思考。將功能分解爲更簡單的塊。有時候在思考整個畫面時,會變得有點費事,很難處理。例如,這個擲骰子在實踐中意味着什麼,或許是先做一個代表骰子的類,類似於;

public class Dice 
{ 
    //declare values 

    Public Dice() 
    { 
    //initialise values 
    } 

    public int rollDice(int times) 
    { 
    // some code here 
    ] 

    public int countStreaks() 
    { 
    // some code here 
    } 
} 

顯然上面的代碼只是一個簡單的例子,但關鍵是上面的類會爲您提供所有你需要建立你的程序的其餘部分基本骰子功能。您的切入點可以簡單地利用這個類來執行您想要的功能。 您應該發現,通過這種方式編程可以帶來許多好處,不僅限於提高生產力,還可以在您希望返回並添加功能或在原始程序之外擴展原始程序時使其更容易。 把這與你上面學習使用數組並看看你如何繼續。一旦你這樣做了,我建議你將新代碼與舊代碼進行比較,以查看其差異。

希望幫助,

問候, V

0
import javax.swing.*; 

進口的java.util。*;

公共類RollThoseDice {

public static void main(String[] args) { 
    //start of method 


    //variables needed for program 
    int total; 
    int newStreak = 1; 
    int streak = 1; 
    int totalIs2 = 0; 
    int totalIs3 = 0; 
    int totalIs4 = 0; 
    int totalIs5 = 0; 
    int totalIs6 = 0; 
    int totalIs7 = 0; 
    int totalIs8 = 0; 
    int totalIs9 = 0; 
    int totalIs10 = 0; 
    int totalIs11 = 0; 
    int totalIs12 = 0; 
    double twoPercent; 
    double threePercent; 
    double fourPercent; 
    double fivePercent; 
    double sixPercent; 
    double sevenPercent; 
    double eightPercent; 
    double ninePercent; 
    double tenPercent; 
    double elevenPercent; 
    double twelvePercent; 

    //intro to program and purpose 
    System.out.println("Today we are going to generate 2 random dice and tally the results of their random combined rolls"); 
    System.out.println("At the bottom of the results, the longest streak will also be listed"); 

    //variable for while loop 
    boolean validInput = true; 
    //declaration of scanner before try/catch 
    Scanner userInput = new Scanner(System.in); 

    //test for valid input 
    while (validInput){ 
     try { 
     int numberOfRolls = Integer.parseInt(JOptionPane.showInputDialog("Please Enter the number of trials you would like to be performed: ")); 

      //Stop from calling for anything else 
      userInput.close(); 

      //declaring of variables for die 1 and die 2 
      int die1[] = new int[numberOfRolls]; 
      int die2[] = new int[numberOfRolls]; 


      //create an array for each die roll so that they can each be saved for recalling streak 
      int[] array = new int[numberOfRolls]; 
      for (int i=1; i<array.length; i++) { 
       die1[i] = (int) ((Math.random() * 6) + 1); 
       die2[i] = (int) ((Math.random() * 6) + 1); 
       total = die1[i] + die2[i]; 

       //streak checker 
       int lastTotal = die1[i-1] + die2[i-1];   
       if (lastTotal == total) { 
        streak++; 
        if (streak > newStreak) { 
         newStreak = streak; 


     /*    // Find-Max variant -- rather than finding the max value, find the 
         // *index* of the max value 
         public int findMaxIndex(int[] nums) { 
          int maxIndex = 0; // say the 0th element is the biggest 
          int maxValue = nums[0]; 

          // Look at every element, starting at 1 
          for (int i=1; i<nums.length; i++) { 
          if (nums[i] > maxValue) { 
           maxIndex = i; 
           maxValue = nums[maxIndex]; 
          } 
          } 
          return maxIndex; 
         } 
*/      

        } 
       } else { 
        streak = 1; 
       } 

       //count total of each numbered possibility rolled 
       if (total == 2) { 
        totalIs2++; 
       } 
       if (total == 3) { 
        totalIs3++; 
       } 
       if (total == 4) { 
        totalIs4++; 
       } 
       if (total == 5) { 
        totalIs5++; 
       } 
       if (total == 6) { 
        totalIs6++; 
       } 
       if (total == 7) { 
        totalIs7++; 
       } 
       if (total == 8) { 
        totalIs8++; 
       } 
       if (total == 9) { 
        totalIs9++; 
       } 
       if (total == 10) { 
        totalIs10++; 
       } 
       if (total == 11) { 
        totalIs11++; 
       } 
       if (total == 12) { 
        totalIs12++; 
       } 
      } 



    //Apply decimal place rounder in order to get percentages rounded to 2 places  



      //calculate percent of each number rolled 
      twoPercent = (totalIs2/(double) numberOfRolls) * 100; 
      threePercent = (totalIs3/(double) numberOfRolls) * 100; 
      fourPercent = (totalIs4/(double) numberOfRolls) * 100; 
      fivePercent = (totalIs5/(double) numberOfRolls) * 100; 
      sixPercent = (totalIs6/(double) numberOfRolls) * 100; 
      sevenPercent = (totalIs7/(double) numberOfRolls) * 100; 
      eightPercent = (totalIs8/(double) numberOfRolls) * 100; 
      ninePercent = (totalIs9/(double) numberOfRolls) * 100; 
      tenPercent = (totalIs10/(double) numberOfRolls) * 100; 
      elevenPercent = (totalIs11/(double) numberOfRolls) * 100; 
      twelvePercent = (totalIs12/(double) numberOfRolls) * 100; 

      //results 
      System.out.println("\n" + "Total Results:"); 
      System.out.println("\n" + "Total 2 happened " + totalIs2 + " times which is " + twoPercent + "%"); 
      System.out.println("Total 3 happened " + totalIs3 + " times which is " + threePercent + "%"); 
      System.out.println("Total 4 happened " + totalIs4 + " times which is " + fourPercent + "%"); 
      System.out.println("Total 5 happened " + totalIs5 + " times which is " + fivePercent + "%"); 
      System.out.println("Total 6 happened " + totalIs6 + " times which is " + sixPercent + "%"); 
      System.out.println("Total 7 happened " + totalIs7 + " times which is " + sevenPercent + "%"); 
      System.out.println("Total 8 happened " + totalIs8 + " times which is " + eightPercent + "%"); 
      System.out.println("Total 9 happened " + totalIs9 + " times which is " + ninePercent + "%"); 
      System.out.println("Total 10 happened " + totalIs10 + " times which is " + tenPercent + "%"); 
      System.out.println("Total 11 happened " + totalIs11 + " times which is " + elevenPercent + "%"); 
      System.out.println("Total 12 happened " + totalIs12 + " times which is " + twelvePercent + "%"); 
      System.out.println("The longest run was a run of " + newStreak + " *number that was on a streak*" + " that began at roll" + "*where it started*"); 

      //stop the loop 
      validInput = false; 
     } 

     //catch exception and call for new input 
     catch(Exception e){ 
      System.out.println("\n" + "Your input was not a number. Please try again: "); 
     } 
    } 
} 

}

0

進口java.text.DecimalFormat中; import java.util。*; //導入實用程序

公共類RollThoseDice {

//private variables for use in code 
private int firstRoll; //initial total to compare with next to scan for streaks 
private int streak; //streak 
private int longestStreak; //longest streak if more than 1 
private int beginningOfLongestStreak; //where in the code the longest streak started for display 
private int[] combineTotal = new int[13]; //total of 2 randomly rolled 6-sided dice 

RollThoseDice(int numberOfRolls) { 
    run(numberOfRolls); 
} 

public void run(int numberOfRolls) { 
    for (int i=0; i<numberOfRolls; i++) { 
     int die1 = (int) ((Math.random() * 6) + 1); //random number between 1-6 
     int die2 = (int) ((Math.random() * 6) + 1); 
     int total = die1 + die2; //math for total 
     combineTotal[total]++; //adding totals to the array 

     if (firstRoll == total) { //comparing 2 rolls in order to see if there is a streak or not 
      streak++; 
      if (streak > longestStreak) { //comparing new streak to old streak to pick the larger of 2 
       longestStreak = streak; 
       beginningOfLongestStreak = i - longestStreak; //getting to the beginning of the streak in order to display to user 
      } 
     } else { 
      streak = 1; 
     } 
     firstRoll = total; 
    } 
} 

private static int readInt(Scanner scanner) { 
    System.out.print(" \n" + "Please enter the number of trials you would like to be performed: "); //prompt user for number of trials (int only) 
    while (!scanner.hasNextInt()) { 
     scanner.next(); 
     System.out.println("\n" + "Your input was not a number. Please try again: "); //drop garbage input 
    } 
    return scanner.nextInt(); //return good input 
} 

public static void main(String[] args) { 
    //intro to program and purpose 
    System.out.println("Today we are going to generate 2 random dice and tally the results of their random combined rolls"); 
    System.out.println("At the bottom of the results, the longest streak will also be listed"); 

    // read number of rolls 
    int numberOfRolls = 0; //casting the number of rolls as 0 initially 
    try(Scanner userInput = new Scanner(System.in)) { 
     numberOfRolls = readInt(userInput); //declaring that the above good input is variable number of rolls 
    } 

    RollThoseDice results = new RollThoseDice(numberOfRolls); 
    DecimalFormat df = new DecimalFormat("###,##0.00"); //round the decimal values 

    //results 
    System.out.println("\n" + "Total Results:"); 
    for (int i = 2; i < results.combineTotal.length; i++) { 
     double percent = (results.combineTotal[i] * 100.0)/numberOfRolls; 
     System.out.println("Total " + i + " happened " + results.combineTotal[i] + " times which is " + df.format(percent) + "%"); //display rolls info 
} 
    System.out.println("\n" +"The longest run was a run of " + results.longestStreak + " that began at roll " + results.beginningOfLongestStreak); //display streak info 
} 

}