2013-10-20 69 views
-1

我需要用特殊變量編寫一個簡單的java程序「滾動骰子」:當用戶滾動骰子時,應用程序滾動兩個骰子,顯示每個骰子的結果,並詢問用戶是否想要再次滾動。編寫一個程序,它具有Main方法和一個用於隨機數生成器的單獨方法。創建一個4個整數變量來存儲兩個骰子,兩個骰子的總和,以及一個擲骰子的次數。一個字符串變量來保存玩家的名字和一個字符變量來保存'y'或'n'。我花了一個小時嘗試做對,但沒有什麼效果。這是我到目前爲止,我不能做更多:滾動兩個骰子java程序

import java.util.Random; 
import java.util.Scanner; 
import javax.xml.validation.Validator; 

public class Main { 




public static void main(String[] args) { 
    System.out.println("Welcome to the Karol’s Roller Application"); 
    System.out.println(); 

    Scanner sc = new Scanner(System.in); 
    String choice = "y"; 

    choice = Validator.getString(sc, "Roll the Dice? (y/n): "); 

    while(choice.equalsIgnoreCase("y")) 
    { 

     choice = Validator.getString(sc, "Roll again? (y/n): "); 


     } 
    } 


Random randomNumbers = new Random();{ 

int dieOne = 0; 
int dieTwo = 0; 
int totals[] = new int[ 13 ]; 

for(int index = 0; index < totals.length; index++) { 
totals[ index ] = 0; 

for(int roll = 1; roll <=4; roll++) { 
    dieOne = (int)(Math.random()*6) + 1; 
    dieTwo = (int)(Math.random()*6) + 1; 
    totals[ dieOne + dieTwo ]++;} 

System.out.println("Roll 1" + 
     "\n " + dieOne + " " + 
     "\n " + dieTwo + " "); 

if (totals[ dieOne + dieTwo ] == 7) 
System.out.println("Craps!" + "\n"); 

else if (totals[ dieOne + dieTwo ] == 2) 
System.out.println("Snake eyes!" + "\n"); 

else if (totals[ dieOne + dieTwo ] == 12) 
System.out.println("Box cars!" + "\n"); 




} 

    } 

} 

請,如果有人能幫助我做正確的這個節目,我有一些問題與,該結果應該或多或少是這樣的:

Welcome to the "name here" Roller Application 

Roll the dice? (y/n): y 

Roll 1: 
number on dice one 
number on dice two 

Roll again? (y/n): y 

Roll 2: 
number on dice one 
number on dice two 

Roll again? (y/n): y 

Roll 3: 
number on dice one 
number on dice two 

Roll again? (y/n): y 

Roll 4: 
number on dice one 
number on dice two 
+0

這不是一個合理的縮進模式,還有一個額外的支架,所以我懷疑它會編譯,我期望你希望擲骰子的東西在while循環中(或者在從那裏調用的輔助方法中定義)。如果有疑問,一次只做一件事,並測試它是否有效。循序漸進的編程方法確實是一條可行的路。 – clwhisk

+0

修復代碼中的身份。它會幫助你更好地找到語法和一些邏輯錯誤。 –

回答

0

您的代碼已完全損壞。考慮什麼呢,當有人不滾snakeseyes發生:

roll1 = 1 
roll2 = 1 
totals[roll1 + roll2]++; -> totals[2] = 1 

再後來你做

if (totals[roll1 + roll2] == 2) { ... 

它永遠不會成功,因爲滾動snakeeyes只會incremenent totals[2]1,而不是2 ...

您根本不需要totals陣列:

if(roll1 + roll2 == 7) { 
    ... craps ... 
} else if (roll1 + roll2 == 2) { 
    ... snake eyes ... 
} else etc.... 
+0

好吧,我解決了總數組的問題,我可以看到變化。可能我不需要像「蛇眼」或「擲骰子」這樣的奇特結果,只是常規總數就可以。我仍然不能做簡單的事情: – user2900919

+0

好吧,我解決了總數組的問題,我可以看到變化。可能我不需要像「蛇眼」或「擲骰子」這樣的奇特結果,只是常規總數就可以。我仍然無法做簡單的事情:「擲骰子?(y/n):y」爲第一次擲骰,「再次擲骰子?(y/n):y」爲其他擲骰。另外當我選擇「n」表示「不」時,它不起作用。我正在尋找我的教科書,以及如何弄清楚如何計算第一卷,第二卷......我剛剛獲得卷1。 – user2900919

+0

對不起,但你需要學習基本的編程。你的代碼只要輸入一個無限循環,除了輸入'y',任何東西都不會調用你的骰子滾動代碼。 –