滚动两个骰子java程序

时间:2013-10-20 20:10:31

标签: java

我需要用特殊变量编写一个简单的java程序“掷骰子”:当用户掷骰子时,应用程序滚动两个骰子,显示每个骰子的结果,并询问用户是否想再次滚动。编写一个具有Main方法的程序和一个用于随机数生成器的单独方法。创建一个4个整数变量来存储两个骰子,两个骰子的总和,以及一个掷骰子的次数。一个字符串变量用于保存玩家的名字,一个字符变量用于保存“y”或“n”。我花了一个小时尝试做对,但没有什么真正有用。这就是我到目前为止所做的一切,我做不了更多:

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

1 个答案:

答案 0 :(得分:0)

您的代码完全被破坏了。考虑当有人滚动蛇眼时会发生什么:

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

然后你做

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

这将永远不会成功,因为滚动的蛇眼只会totals[2]增加到1,而不是2 ...

您根本不需要totals数组:

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