-1

我需要编写一个带有特殊变量的简单 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
4

1 回答 1

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....
于 2013-10-20T20:14:42.710 回答