2016-04-03 48 views
-2

我想獲得一些我正在編寫的程序的幫助。我想輸出兩個,他們的臉部頻率加在一起。這是我寫的最新代碼。現在非常基本,寫得很差。我對Java編碼非常陌生,所以請給我任何提示和技巧,以幫助我:)。如何輸出兩個骰子並將它們加在一起

import java.util.Random; 

public class DiceRolling { 

    public final static Random randomNumbers = new Random(); 

    public static void main(String[] args) { 

     int[] dice1 = new int[7]; 
     int[] dice2 = new int[7]; 

     // prints out the headings 

     for (int headOne = 1; headOne <= 6; headOne++) 
      System.out.print(" " + headOne); 

     System.out.println(); 

     for (int headTwo = 1; headTwo <= 6; headTwo++) 
      System.out.println(headTwo); 

     // The rolls of the two dices begins here 

     for (int frequencyOne = 0; frequencyOne < 36000000; frequencyOne++) { 
      ++dice1[1 + randomNumbers.nextInt(6)]; 
     } 

     // output faces of die 
     for (int faceOne = 1; faceOne < dice1.length; faceOne++) { 
      System.out.print(" " + dice1[faceOne]); 
     } 
    } 

} 
+3

什麼問題?有什麼不起作用嗎?爲什麼要導入'java.lang.reflect.Array'? – Thilo

+1

'dice2'永遠不會被使用,那是故意的嗎?你應該問一個更具體的問題。 –

回答

-1

以下代碼將打印出每個面的滾動次數。由於Random java庫使用的隨機數算法,您將注意到所有面的滾動次數幾乎相同。如果您有任何疑問,請提問!

import java.util.HashMap; 
import java.util.Map.Entry; 
import java.util.Random; 

public class DiceRolling { 

    public final static Random randomNumbers = new Random(); 

    public static void main(String[] args) { 
     // create a hashmap to hold the amount of times each number was rolled 
     HashMap<Integer, Integer> frequencies = new HashMap<Integer, Integer>(); 

     // roll the dice 360000 times 
     for (int rolls = 0; rolls < 360000; rolls++) { 
      // roll dice 
      int result = (randomNumbers.nextInt(6) + 1); 

      // if the result has already happened add it 
      if (frequencies.containsKey(result)) { 
       frequencies.put(result, (frequencies.get(result) + 1)); 
       continue; 
      } 
      // else add it and set its frequency to 1 
      frequencies.put(result, 1); 
     } 

     // print results 
     for (Entry<Integer, Integer> entry : frequencies.entrySet()) { 
      System.out.println("Face: " + entry.getKey() + ", Times rolled: " + entry.getValue()); 
     } 
    } 
} 
+0

謝謝!現在我有了一個更好的理解。 – Nomide

相關問題