2017-02-10 52 views
0

我一直在編程一個彩票模擬,有一些幫助,我在這個網站上看到的問題。我似乎無法讓程序顯示我需要的正確數量的結果,而且這兩套不能正確比較有多少數字匹配。Java抽獎模擬使用集合,不產生正確數量的隨機結果或正確比較設置

import java.util.Set; 
import java.util.HashSet; 
import java.util.Random; 
import java.util.Scanner; 

public class Lotto { 
    private static final int INPUT_SIZE = 6; 

    private static final int MIN_NUMBER_POSSIBLE = 1; 
    private static final int MAX_NUMBER_POSSIBLE = 10; 

    private Set<Integer> userNumbers = new HashSet<Integer>(); 
    private Set<Integer> randomNumbers = new HashSet<Integer>(); 

    public static void main(String[] args) { 
     Lotto c = new Lotto(); 
     c.generateRandomNumbers(); 
     System.out.println("Please choose " + INPUT_SIZE + " numbers from " + MIN_NUMBER_POSSIBLE + " to " + MAX_NUMBER_POSSIBLE + ", hit enter after each number."); 
     c.readUserNumbers(); 

     if (c.doUserNumbersMatchRandomNumbers()) { 
      System.out.println("Congratulations, you have won!"); 
     } else { 
      System.out.println("Not a winner, better luck next time."); 
      c.showRandomNumbersToUser(); 
     } 
    } 

    private void generateRandomNumbers() { 
     Random random = new Random(); 
     for (int i = 0; i < INPUT_SIZE; i++) { 
      randomNumbers.add(random.nextInt(MAX_NUMBER_POSSIBLE)); 
     } 
    } 

    private void showRandomNumbersToUser() { 
     System.out.println("\nLotto numbers were : "); 
     for (Integer randomNumber : randomNumbers) { 
      System.out.println(randomNumber + "\t"); 
     } 
    } 

    private void readUserNumbers() { 
     Scanner input = new Scanner(System.in); 
     int inputSize = 1; 
     while (input.hasNextInt() && inputSize < INPUT_SIZE) { 
      int numberChosen = input.nextInt(); 
      if (numberChosen < MIN_NUMBER_POSSIBLE || numberChosen > MAX_NUMBER_POSSIBLE) { 
       System.out.println("Your number must be in " + MIN_NUMBER_POSSIBLE + " - " + MAX_NUMBER_POSSIBLE + " range."); 
      } else { 
       userNumbers.add(numberChosen); 
       inputSize++; 
      } 
     } 
    } 

    private boolean doUserNumbersMatchRandomNumbers() { 
     for (Integer userNumber : userNumbers) { 
      for (Integer randomNumber : randomNumbers) { 
       if (!randomNumbers.contains(userNumber)) { 
        return false; 
       } 
      } 
      printMatchingNumber(userNumber); 
     } 
     return true; 
    } 

    private void printMatchingNumber(int num) { 
     System.out.println("Your number, " + num + ", has been drawn."); 
    } 
} 
+0

請記住,一個'Set'會刪除重複項,這意味着如果該值已經在'Set'中,'add'將被忽略。 – 4castle

回答

1

有兩個問題在你的代碼:

1)generateRandomNumbers,你應該考慮到的是,相同的隨機數可能發生多次。所以請確保randomNumbers的尺寸最終確實是INPUT_SIZE

2)在doUserNumbersMatchRandomNumbers中,您重複使用randomNumbers,但從不使用randomNumber

0

您存儲的隨機數的(Hash - )Set,如API描述Set一個特點是,它們不包含重複值(由他們與他們的equals()方法相比)。由於Random類可能會多次輸出相同的值,因此您的Set中的值較少。

產生的隨機數是去同一個while循環更好的方法:

while (random.size() < INPUT_SIZE) 
{ 
    randomNumbers.add(random.nextInt(MAX_NUMBER_POSSIBLE)); 
} 

記住,這可能會導致死循環。雖然這是不太可能的。至少這個循環確實有不同的執行時間。