2015-04-06 75 views
0

這是我的代碼..我不認爲我正確使用do/while循環...如何讓代碼再次嘗試?

我該如何正確使用do/while?

我應該使用不同的方法嗎?

我想知道

public static void main(String[] args) { 
    // TODO code application logic here 
    Scanner input = new Scanner(System.in); 
    System.out.print("enter minimum of Yahtzee dice 2-9:"); 
    int min = input.nextInt(); 
    System.out.print("enter maximum of Yahtzee dice 3-10:"); 
    int max = input.nextInt(); 
    String tryAgain = "y"; 
    do { 
    System.out.println("Dice Rolls\tYahtzee's Percentage Odds\t"); 
    for (int i = min; i <= max; i++) { 
     int count = 0; 
     boolean success = true; 
     for (int j = 0; j <= 5000000; j++) { 
      Random generator = new Random(); 
      YahtzeeDice d = new YahtzeeDice(generator, i); 
      if (d.IsAYahtzee()) { 
       count++; 
      } 
     } 
     System.out.printf("%d  ", i); 
     System.out.printf("%d\t", 5000000); 
     System.out.printf("%d\t ", count); 
     System.out.printf("%f ", (double) count/5000000); 
     double per = count/(double) 5000000; 
     int odds = (int) (1/per); 
     System.out.printf("1 in %d\n", odds); 
    } 
     System.out.print("Run another simulation [y/n]? "); 
     tryAgain = input.nextLine(); 
} while(!tryAgain.equals("n")); 

回答

0

immibis如何在第一評論釘吧,我想。你非常接近正確。試試這個:

public static void main(String[] args) { 
     // TODO code application logic here 
     Scanner input = new Scanner(System.in); 
     Random generator = new Random(); 

     String tryAgain = "y"; 
     do { 
      System.out.print("enter minimum of Yahtzee dice 2-9:"); 
      int min = input.nextInt(); 
      input.nextLine(); 
      System.out.print("enter maximum of Yahtzee dice 3-10:"); 
      int max = input.nextInt(); 
      input.nextLine(); 

      System.out.println("Dice Rolls\tYahtzee's Percentage Odds\t"); 

      for (int i = min; i <= max; i++) { 
       int count = 0; 
       boolean success = true; 
       for (int j = 0; j <= 5000; j++) { 
        YahtzeeDice d = new YahtzeeDice(generator, i); 
        if (d.IsAYahtzee()) { 
         count++; 
        } 
       } 
       System.out.printf("%d  ", i); 
       System.out.printf("%d\t", 5000000); 
       System.out.printf("%d\t ", count); 
       System.out.printf("%f ", (double) count/5000000); 
       double per = count/(double) 5000000; 
       int odds = (int) (1/per); 
       System.out.printf("1 in %d\n", odds); 
      } 

      System.out.print("Run another simulation [y/n]? "); 
      tryAgain = input.nextLine(); 

     } while (!tryAgain.equals("n")); 

} 

ps。在玩耍的時候,我不知道你在做什麼,而是移動了你的輸入。你應該將它們移回循環之外,如果這就是你的意圖。

+0

非常感謝你~~~ !!! –

相關問題