2014-09-23 74 views
0

我正在製作一個骰子模擬器,我的任務是一次擲4個骰子,疊加骰子的每個面,然後重複該過程多次。然後我必須記錄每卷(添加4個骰子)發生多少次,並製作一張桌子。Java中的骰子程序

我基本上正在努力的是如何循環我的代碼,以便它可以根據需要多次重複滾動,並跟蹤每個滾動的數值。這是我到目前爲止的代碼:

這是我對模具方案:

import java.util.Random; 

public class Die 
{ 
    private Random generator; 
    private int sides; 
    public Die (int s) 
    { 
     sides = s; 
     generator = new Random(); 
    } 

    public int cast() 
    { 
     return 1 + generator.nextInt(sides); 
    } 
} 

這是我的模具模擬程序:

import java.util.Scanner; 
import java.util.Random; 

public class DieSimulator 
{ 
    public static void main(String[] args) 
    { 
     Die d1 = new Die(6); 
     Die d2 = new Die(6); 
     Die d3 = new Die(6); 
     Die d4 = new Die(6); 
     final int TRIES = 1; 
     for (int i = 1; i <= TRIES; TRIES +) 
     { 
     int n1 = d1.cast(); 
     //System.out.print(n1 + ""); 
     int n2 = d2.cast(); 
     //System.out.print(n2 + ""); 
     int n3 = d3.cast(); 
     //System.out.print(n3 + ""); 
     int n4 = d4.cast(); 
     System.out.print(n4 + n3 + n2 + n1); 
     n = n4 + n3 + n2 + n1 

     } 
     System.out.println(); 
    } 
} 

模具模擬器程序的註釋部分是隻是我試圖找出如何發佈卷的數值。

任何幫助,將不勝感激

+1

什麼是你的程序的終止條件:

**int [][] results = new int[nDices][nRolls];** 

您遍歷每個被輕易扔掉?它應該什麼時候停止?你現在也沒有跟蹤每一卷。 – mkobit 2014-09-23 06:04:07

+0

你可以expalin你的意思嗎只是我試圖找出如何發佈卷的數值。 – 2014-09-23 06:05:12

+5

這是甚至編譯? :for(int i = 1; i <= TRIES; TRIES +)' – 2014-09-23 06:06:09

回答

0

您可以創建一個新的類,它有四個骰子涉及:冷軋值的

public class Dice { 
    private Die[] dice; 
    public Dice(int noOfDice, int maxValueOfDice) { 
     dice = new Die[noOfDice]; 
     for(int i = 0; i < dice.length; ++i){ 
      dice[i] = new Die(maxValueOfDice); 
     } 
    } 
    public int cast(){ 
     int sum = 0; 
     for(Die d : dice){ 
      sum += d.cast(); 
     } 
     return sum; 
    } 
} 

飼養的軌道是可以通過使用地圖或數組:

import java.util.HashMap; 
import java.util.Map; 

public class Statistics { 
    static int TRIES = 1000; 
    public static void main(String[] args) 
    { 
     Dice dice = new Dice(4, 6); 
     Map<Integer,Integer> map = new HashMap<>(); 
     // roll TRIES times 
     for (int i = 1; i <= TRIES; ++i){ 
      int value = dice.cast(); 
      if(map.containsKey(value)){ 
       map.put(value, map.get(value)+1); 
      } else { 
       map.put(value,1); 
      } 
     } 
     // print all results: 
     for(Integer key : map.keySet()){ 
      System.out.println("Value " + key + " rolled " + map.get(key) + " times"); 
     } 
    } 
} 
0

我真的很喜歡你的程序的結構,但我認爲這將是非常簡單的,如果你不打擾另一個類。

保留每個單獨卷繞的軌道的最簡單方法是:

Random r = new Random(); 
int currSum=0; 
int oneRollSum=0; 
for(int i=0; i<nRolls;i++){ 
    for(int j=0; j<nDices; j++){ 
     results[j][i]= r.nextInt(6)+1; 
     oneRollSum=oneRollSum+results[j][i]; 
     currSum=results[j][i]+currSum; 
    } 
    oneRollSum=0; 

}