2017-10-11 42 views
-3

我已經有下列要求:隨機票用的if-else爲偏彩票

public class RandomTickets 
{ 
    public static void main(String[] args) 
    { 
     final int MIN = 0, MAX = 3; 
     int ticketQuant = ((int)(Math.random() * (MAX + 1 - MIN))) + MIN; 

     System.out.println(); 
     System.out.print("You have won " + ticketQuant); 
     System.out.println(ticketQuant == 1 ? " ticket." : " tickets."); 
     System.out.println(); 
    } 
} 

但我想要做的是改變計劃,以便有:

  • 1 15在中獎票1的15勝算贏得2張
  • 4的15機會3張車票
  • 2的機會

我想使用switch語句。

有什麼想法?

+2

如何產生1至15(含)之間,而不是一個號碼?如果這個數字小於或等於'4',那麼至少有一張票已經贏了。等(嵌套'如果'檢查其他兩個條件)。 –

+0

作爲我上面評論的附錄,使用帶有突破情況的開關是我解決問題的方法。 「4」和「3」的一種常見情況,「2」和「1」最後一種情況。每種情況下,「票據」變量增加1(當然最初初始化爲零)。在切換之後,「ticket」變量將以您想要的概率爲「1」,「2」或「3」。 –

+0

或者我誤解了你和概率?無關緊要,只需調整'if'語句中的條件,以確保有四個數字有效(例如'randomNumber> = 4 && randomNumber <= 7')。仍然可以用開關來解決,但現在使用'if'更有意義。如果沒有任何「其他」,你仍然可以用「if」來「穿過」。然後就像跌落切換案例一樣,只需在每個「if」中將「票據」變量加1即可。 –

回答

0

非常簡單的解決方案:

final Random random = new Random(); 
final int r = 1 + random.nextInt(15); 
final ticketCount; 

if (r <= 4) { 
    ticketCount = 1; 
} else if (r <= 6) { 
    ticketCount = 2; 
} else if (r <= 7) { 
    ticketCount = 3; 
} 

略偏花式:

ticketCount = ((r^15) == 0 ? 3 : 0) + 
    (((r | 1)^9) == 0 ? 2 : 0) + 
    (((r | 3)^7) == 0 ? 1 : 0); 
0
// Designate numbers for each luck 
    final List<Integer> luck1OutOf15 = Arrays.asList(1); 
    final List<Integer> luck2OutOf15 = Arrays.asList(2, 3); 
    final List<Integer> luck4OutOf15 = Arrays.asList(4, 5, 6, 7); 

    final Random random = new Random(); 
    final int luck = random.nextInt(15) + 1; 
    final int ticketCount; 
    if (luck1OutOf15.contains(luck)) { 
     ticketCount = 3; 
    } else if (luck2OutOf15.contains(luck)) { 
     ticketCount = 2; 
    } else if (luck4OutOf15.contains(luck)) { 
     ticketCount = 1; 
    } else { 
     ticketCount = 0; 
    }