2016-02-11 51 views
0

我想要讓這個硬幣折騰程序爲Java工作。我還是很新的,我很確定我搞砸了一堆。任何人都可以看看嗎?無法弄清楚如何讓我的開關保持循環,直到用戶輸入0來停止硬幣翻轉:枚舉硬幣折扣程序卡住

主要目標是詢問用戶有多少翻轉和出多少頭和尾翻轉。然後詢問他們是否想繼續翻轉並將這些翻轉添加到已經完成的翻轉中,並且我必須使用ENUM來完成翻轉。 。 。

import java.util.Random; 
import java.util.Scanner; 

public class CoinTossing { 

    private enum Coin { HEADS, TAILS }; 

    private static final Random randomNumbers = new Random(); 

    private static final int HEADS = 1; 
    private static final int TAILS = 2; 




    public static void main(String[] args) 
    { 

     Scanner input = new Scanner (System.in); 

     int quantity = 0; 
     int headSide = 0; 
     int tailsSide = 0; 


     System.out.println("How many times would you like to flip the coin? Enter 0 to end."); 
     int flipNumber = input.nextInt(); 

     while (flipNumber != 0) 


      quantity = quantity + flipNumber; 

      for(int x=1; x<=quantity; ++x); 

       switch (Flip(null)) 
       { 

       case HEADS: 
        headSide++; 
        break; 

       case TAILS: 
        tailsSide++; 
        break; 

       } 


       if (flipNumber == 0) 
        System.out.println("Your Number of flips is" + HEADS +TAILS); 
    } 

    private static int Flip(Random randomNumber) { 
     int toss; 

     toss = 1+ randomNumber.nextInt(2); 
     return toss; 
    } 
} 
+0

Java不是python,縮進在這裏只用於可讀性目的,它不影響範圍。 – Pshemo

+0

又是什麼'''在這裏做:'for(int x = 1; x <= quantity; ++ x);'? – Pshemo

回答

0

據我所知,你不實際發送任何類型的隨機數生成器,爲你傳遞的參數是null。我會建議實例,然後試圖將它傳遞在

關閉我的頭頂,加入這一行: Random random = new Random(); 然後改變開關 switch (Flip(random)) 可以解決您的問題。

+0

他還爲'HEADS'和'TAILS'定義了'enum'和'int'。 – callyalater

+0

實際上,他定義了一個靜態變量'randomNumbers',並且已經被實例化... –

0

您的while循環沒有超出quantity = quantity + flipNumber;的範圍。如果您打算讓while循環包含for循環,請確保包含大括號。

3
while (flipNumber != 0) 



    quantity = quantity + flipNumber; 

這個循環永遠不會中斷。如果沒有括號,這是一個單行循環相當於

while (flipNumber != 0) 
{ 
    quantity = quantity + flipNumber; 
} 

顯然,如果flipNumber不爲0,這個循環將永遠運行下去。

0
public class CoinTossing {  
    private enum Coin { HEADS, TAILS } 
    private static final Random random = new Random(); 

    public static void main(String[] args) { 
    Scanner input = new Scanner(System.in);  
    int headSide = 0; 
    int tailsSide = 0; 

    System.out.println("How many times would you like to flip the coin? Enter 0 to end."); 

    int flipNumber; 

    while ((flipNumber = input.nextInt()) != 0) { 
     for (int x = 0; x <= flipNumber; x++) { 
     switch (flip()) { 
      case HEADS: 
      headSide++; 
      break; 
      case TAILS: 
      tailsSide++; 
      break; 
     } 
     } 
     System.out.printf("Heads: %d Tails: %d\n", headSide, tailsSide); 
    } 
    System.out.println("Your number of flips is " + (headSide + tailsSide)); 
    } 

    private static Coin flip() { 
    if (random.nextBoolean()) { 
     return Coin.HEADS; 
    } else { 
     return Coin.TAILS; 
    } 
    } 
}