2017-10-11 11 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(); 
    } 
} 

をしかし、私がやりたいことがあるようにプログラムを変更することです:15で

  • 1 1枚のチケットの勝利の15チャンスで2枚のチケット
  • 4の勝利の15チャンスで3枚のチケット
  • 2の勝利のチャンス

そして、switch文を使いたいと思います。

どのようなアイデアですか?

+2

方法の代わりに(包括的)1〜15の番号を生成するでしょうか?その数が「4」以下であれば、少なくとも1つのチケットが獲得されている。そうすることで(もし 'if'が入れ子になっていると他の2つの条件がチェックされます)。 –

+0

上記のコメントの補足として、フォールスルーケースのスイッチを使用して解決する方法です。 '4'と' 3'の共通のケース、 '2'のためのもの、' 1'のためのものです。それぞれの場合は、「チケット」変数を1つインクリメントします(当初はゼロに初期化されています)。スイッチの後、 "ticket"変数はあなたが望む確率で '1'、' 2'または '3'になります。 –

+0

またはおそらく私はあなたとその確率を誤解していますか?重要ではありませんが、正確に4つの数字が有効になるように 'if'文の条件を調整するだけです(例えば' randomNumber> 4 && randomNumber <= 7')。スイッチでも解決できますが、今は 'if'を使うのが少し意味があります。あなたは '' else'を持たないことで、 '' if ''を使って "落ちる"ことができます。そして、fall-throughスイッチの場合と同じように、各if変数の "tickets"変数を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; 
    }