2013-01-08 433 views
2

我搜索了,根本找不到我的問題的答案。 我必須創建一個樂透類型模擬,6個數字+獎勵號碼,沒有重複。 我已經管理得到它的工作,但在6號碼陣列中poistion [1]的數字始終爲0。我確信它的簡單問題,但我是全新的,所以任何幫助將感激下面accepted.Code,我敢肯定,它的所有的地方........在java數組中不重複的隨機數字

import java.util.Arrays; 

public class Lotto { 

    public static void main(String[] args) { 

     int[] Lotto=new int[6]; 
     final int MIN = 1; 
     final int MAX = 45; 

     for (int i = 0; i< Lotto.length; ++i) 
     { 

      Lotto [0] =MIN+ (int)(Math.random()*((MAX -MIN)+1)); 

      while (Lotto[1] == Lotto[0]) 
      { 
       Lotto[1] =MIN+ (int)(Math.random()*((MAX -MIN)+1)); 
      } 

      while ((Lotto[2] == Lotto[0]) || (Lotto[2] == Lotto[1])) 
      { 
       Lotto[2] = MIN+ (int)(Math.random()*((MAX -MIN)+1)); 

      while ((Lotto[3] == Lotto[0]) || (Lotto[3] == Lotto[1]) || (Lotto[3] == Lotto[2])) 
      { 
       Lotto[3] = MIN+ (int)(Math.random()*((MAX -MIN)+1)); 
      } 

      while ((Lotto[4] == Lotto[0]) || (Lotto[4] == Lotto[1]) || (Lotto[4] == Lotto[2]) || (Lotto[4] == Lotto[3]))       

      { 
       Lotto[4] = MIN+ (int)(Math.random()*((MAX -MIN)+1)); 



       while ((Lotto[5] == Lotto[0]) || (Lotto[5] == Lotto[1]) || (Lotto[5] == Lotto[2]) || (Lotto[5] == Lotto[3])|| (Lotto[5] == Lotto[4])) 

       { 
        Lotto[5] = MIN+ (int)(Math.random()*((MAX -MIN)+1)); 
       } 


       int[] BonusNumber=new int[1]; 
       for (int j = 0; j< BonusNumber.length; ++j) 
       { 

        BonusNumber [j] =1+ (int)(Math.random()*((45 -1)+1)); 
       } 

       System.out.println("Winner " + Arrays.toString(Lotto)); 
       System.out.println("Bonus Number" +Arrays.toString(BonusNumber)); 
      { 


    } 
      } 
      } 
     } 
    } 
} 

回答

2

您可以使用HashSet這使沒有秩序,也沒有重複。

每當你需要一個新的隨機數時,你也可以創建一個java.util.Random類的新實例,因爲這改變了種子,並且會給你的應用程序更多的隨機性,從而消除每次包含0的位置1。

new java.util.Random().nextInt(int max)

5

更改這個循環:

while (Lotto[1] == Lotto[0]) 
{ 
    Lotto[1] = random(MIN, MAX); 
} 

到:

do { 
    Lotto[1] = random(MIN, MAX); 
} while (Lotto[1] == Lotto[0]); 

和代碼的相應其餘部分。你看到問題出在哪裏?

但在開始之前,你重寫相當複雜和難以維護的代碼,看看這個實現,這是非常容易理解和正確...:

final int MIN = 1; 
final int MAX = 45; 

final List<Integer> allPossible = new ArrayList<Integer>(MAX - MIN + 1); 
for (int i = MIN; i <= MAX; ++i) { 
    allPossible.add(i); 
} 
Collections.shuffle(allPossible); 
final List<Integer> lotto = allPossible.subList(0, 6); 
int bonusNumber = allPossible.get(6); 

System.out.println("Winner "  + lotto); 
System.out.println("Bonus Number" + bonusNumber); 

Collections.shuffle()在這裏至關重要。

+0

Tomasz,非常感謝,我現在看到它。無法保持它可能,但我必須堅持我的課程文本,我們沒有涵蓋集合,所以我不能使用它,似乎愚蠢,但多數民衆贊成在他們想要的方式,只有2個月,所以我們肯定會覆蓋這一切。 – user1958789

3

我覺得你的代碼是相當混亂,你可以通過使用一些API工具,如Collections.shuffle()在這個例子中避免這麼多的條件:

public static void main(String[] args) 
{ 
    Integer[] numbers = new Integer[45]; 

    // Populating numbers. 
    for (int i = 0; i < 45; i++) 
     numbers[i] = i + 1; 

    // Shuffling them to make them in random order. 
    List<Integer> list = Arrays.asList(numbers); 
    Collections.shuffle(list); 

    // Print any 6 of them. I chose first 6 ones for simplicity. 
    for (int i = 0; i < 6; i++) 
     System.out.print(list.get(i) + " "); 
} 

輸出示例:

15 11 31 2 5 38 
+0

你有一個錯誤的錯誤,OP希望從'1'到'45'的值,你從'0'返回到'44'。 –

+0

@TomaszNurkiewicz很好的調試,謝謝=)現在,這是OK。 – Juvanis

+0

沒問題。但是,我是否可以建議僅僅從'1'迭代到'<= 45'以避免45' + 1'操作? Microoptimization,但一個簡單的勝利。 –

1

如果你想使用int []而不是內置的類,你可以做

int[] ints = new int[45]; 
for (int i = 0; i < ints.length; i++) ints[i] = i + 1; 
Random rand = new Random(); 
for (int i = 0; i < 6; i++) { 
    int swap = rand.nextInt(ints.length - i) + i; 
    int tmp = ints[i]; 
    ints[i] = ints[swap]; 
    ints[swap] = tmp; 
} 
int[] drawn = Arrays.copyOf(ints, 6); 
System.out.println(Arrays.toString(drawn)); 

打印

[19, 22, 24, 6, 34, 23] 
0

我覺得我走的是同樣的介紹Java類,你(作爲程序看起來出奇的熟悉),所以我會盡量保持它只是基本的東西;然而,我從程序中複製了所有的原始代碼,所以你基本上做了所有的工作,我只是把它清理了一下。

這是一個完整的程序(隨機化一組數字(檢查重複),允許用戶選擇一套或隨機化自己的(也檢查重複),排序和比較兩套,通知用戶是否他們贏了還是不行,要求再次上場:

import java.util.*; 
    public class Lotto 
    { 
    public static void main(String[] args) 
    {   
     Scanner keyboard = new Scanner(System.in); 
     Random rand = new Random(); 
     boolean checkPlay = false, readInput = false; 
     final int MAX = 45; 

     while (readInput != true) 
     { 
      System.out.print("Would you like to buy a lotto ticket? [y/n] "); 
      String stBuyTicket = keyboard.nextLine().trim().toLowerCase(); 

      if (stBuyTicket.isEmpty()) 
      { 
       System.out.println("Invalid Input."); 
      } 
      else if (stBuyTicket.charAt(0) == 'y' || stBuyTicket.charAt(0) == 'n') 
      { 
       if (stBuyTicket.charAt(0) == 'y') 
       { 
        checkPlay = true; 
       } 
       else 
       { 
        checkPlay = false;      
       } 
       readInput = true; 
      } 
      else 
      { 
       System.out.println("Invalid Input."); 
      } 
     }   
     while (checkPlay == true) 
     { 
      int[] lotto = new int[6]; 
      int lottoLength = lotto.length; 
      int[] userLotto = new int[6]; 
      int userLottoLength = userLotto.length; 
      for (int i = 0; i < lottoLength; i++) 
      { 
       boolean checkLotto = false; 
       while (checkLotto != true) 
       { 
        int numCheck = (rand.nextInt(MAX) + 1); 
        boolean confirmSame = false; 
        for (int j = 0; j <= i; j++) 
        { 
         if (numCheck == lotto[j]) 
         { 
          confirmSame = true; 
         } 
        } 
        if (confirmSame != true) 
        { 
         lotto[i] = numCheck; 
         checkLotto = true;            
        } 
       } 
      }    
      readInput = false; 
      while (readInput != true) 
      { 
       System.out.println("Would you like choose your own numbers or just randomize them?"); 
       System.out.print("Choose your own numbers? [y/n] ");    
       String stBuyTicket = keyboard.nextLine().trim().toLowerCase(); 
       if (stBuyTicket.isEmpty()) 
       { 
        System.out.println("Invalid Input."); 
       } 
       else if (stBuyTicket.charAt(0) == 'y' || stBuyTicket.charAt(0) == 'n') 
       { 
        if (stBuyTicket.charAt(0) == 'y') 
        { 
         for (int i = 0; i < userLottoLength; i++) 
         { 
          boolean checkUserLotto = false; 
          while (checkUserLotto != true) 
          { 
           System.out.print("Which number would you like to choose for number " + (i + 1) + ": "); 
           String numUserInput = keyboard.nextLine().trim(); 

           int numUserInputLength = numUserInput.length(); 
           boolean checkInput = true; 
           if (numUserInputLength > 2 || numUserInputLength < 1) 
           { 
            System.out.println("Invalid Input. Try again."); 
            checkInput = false; 
           } 
           else 
           { 
            for (int j = 0; j < numUserInputLength; j++) 
            { 
             if (Character.isDigit(numUserInput.charAt(j)) != true) 
             { 
              System.out.println("Invalid Input. Try again."); 
              checkInput = false; 
             } 
            } 
           } 
           if (checkInput == true) 
           { 
            int userInput = Integer.parseInt(numUserInput); 
            if (userInput > MAX || userInput < 1) 
            { 
             System.out.println("Invalid Input. Try again."); 
            } 
            else 
            { 
             boolean confirmSame = false; 
             for (int j = 0; j <= i; j++) 
             { 
              if (userInput == userLotto[j]) 
              { 
               System.out.println("You've already choosen this number. Choose again."); 
               confirmSame = true; 
              } 
             } 
             if (confirmSame != true) 
             { 
              userLotto[i] = userInput; 
              checkUserLotto = true; 
             } 
            } 
           } 
          } 
         } 
        } 
        else 
        { 
         for (int i = 0; i < userLottoLength; i++) 
         {        
          boolean checkLotto = false; 
          while (checkLotto != true) 
          { 
           int numCheck = (rand.nextInt(MAX) + 1); 
           boolean confirmSame = false;         
           for (int j = 0; j <= i; j++) 
           { 
            if (numCheck == userLotto[j]) 
            { 
             confirmSame = true; 
            } 
           } 
           if (confirmSame != true) 
           { 
            userLotto[i] = numCheck; 
            checkLotto = true;            
           } 
          } 
         } 
        } 
        readInput = true; 
        System.out.print("Your lotto numbers are: " + userLotto[0]); 
        for (int i = 1; i < userLottoLength; i++) 
        { 
         System.out.print(", " + userLotto[i]); 
        } 
        System.out.print("!"); 
        System.out.println(); 

        System.out.print("And the winning lotto numbers are: " + lotto[0]); 
        for (int i = 1; i < lottoLength; i++) 
        { 
         System.out.print(", " + lotto[i]); 
        } 
        System.out.print("!"); 
        System.out.println(); 

        Arrays.sort(lotto); 
        Arrays.sort(userLotto); 

        if (Arrays.equals(userLotto, lotto) == true) 
        { 
         System.out.println("Your lotto numbers match the winning lotto numbers! \nYou win!"); 
        } 
        else 
        { 
         System.out.println("Your lotto numbers do not match the winning lotto numbers. \nYou lose."); 
        } 
       } 
       else 
       { 
        System.out.println("Invalid Input."); 
       } 
      } 
      readInput = false; 
      while (readInput != true) 
      { 
       System.out.print("Would you like to buy another lotto ticket? [y/n] "); 
       String stBuyTicket = keyboard.nextLine().trim().toLowerCase(); 

       if (stBuyTicket.isEmpty()) 
       { 
        System.out.println("Invalid Input."); 
       } 
       else if (stBuyTicket.charAt(0) == 'y' || stBuyTicket.charAt(0) == 'n') 
       { 
        if (stBuyTicket.charAt(0) == 'y') 
        { 
         checkPlay = true; 
        } 
        else 
        { 
         checkPlay = false; 
        } 
        readInput = true; 
       } 
       else 
       { 
        System.out.println("Invalid Input."); 
       } 
      } 
     } 
     System.out.println("That's a good decision. Save your money"); 
     System.exit(0); 
    } 
} 

以下是隨機化樂透集而不repitition部分:

for (int i = 0; i < lottoLength; i++) { 
       boolean checkLotto = false; 
       while (checkLotto != true) { 
        int numCheck = (rand.nextInt(MAX) + 1); 
        boolean confirmSame = false; 
        for (int j = 0; j <= i; j++) { 
         if (numCheck == lotto[j]) { 
          confirmSame = true; 
         } 
        } 
        if (confirmSame != true) { 
         lotto[i] = numCheck; 
         checkLotto = true;            
        } 
       } 
      } 

它會產生一些與int numCheck = (rand.nextInt(MAX) + 1),並檢查數量對每一個輸入樂透號碼到目前爲止:

for (int j = 0; j <= i; j++) { 
    if (numCheck == lotto[j]) { 
     confirmSame = true; 
    } 
} 

如果numCheck不等於任何輸入的號碼時,則numCheck被寫入到當前的陣列點。