1

私のプログラムの目標は、最初に1〜6の乱数を生成して「ポイント」と呼び、次にユーザーはキーを入力し続けて、並べられた「サイコロ」を再ロールすることです。同じ番号がロールされた場合、ユーザーは最初のifステートメントからのメッセージでプロンプトが表示されます

ただし、次のサイコロが振られるたびに、それがポイント番号に振られることはなく、最初のifステートメントの印刷行がランダムに印刷されます。これを修正する方法についての回答をいただければ幸いです。

import java.io.*;

public class DiceGame1
{
  public static void main (String [] args) throws IOException
  {

    String userInput;
    int DiceRoll;
    int exit = 0;


    BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
    System.out.println("Hello, this program rolls a dice and outputs the number rolled");

    System.out.println("The number rolled is called the point it will keep rolling untill it");
    System.out.println("hits that point again, press any key to con't");

    userInput = myInput.readLine();

    DiceRoll = (int) (Math.random () *(6-1) + 1);

    System.out.println("The point to match is: " + DiceRoll);
    System.out.println("Press any key to roll again...");
    userInput = myInput.readLine();

    while(exit != 999) {
      int nextRoll = (int) (Math.random () *(6-1) + 1);

      if (nextRoll == DiceRoll)
      {
        System.out.println(" It took the computer _____ tries to reach the point");
      }
      else 
      {
        System.out.println("The roll is : " + nextRoll);
        System.out.println("Press any key to roll again...Or press '999' to exit");
        userInput = myInput.readLine();
      }  
    }
  }
}
4

2 に答える 2

2

ループの終了条件はexit == 999です。exitただし、ループ内で値を割り当てることはありません。したがって、それは際限なくループします。

さらに、サイコロの値が最初のロールと等しくない場合にのみ、サイコロの値を印刷します。そして、そうではありません。そのため、最初のメッセージは印刷されるべきではないときに印刷されるという印象を受けました。

于 2013-03-04T22:31:19.850 に答える
1

あなたが探しているのは、たとえそれがマッチであっても、常にサイコロを振らなければならないことだと思います。これは、次のように、else句の外側への印刷と入力を削除することで実現できます。

  if (nextRoll == DiceRoll)
  {
    System.out.println(" It took the computer _____ tries to reach the point");
  }
  else 
  {
    System.out.println("The roll is : " + nextRoll);
  }  
   System.out.println("Press any key to roll again...Or press '999' to exit");
   userInput = myInput.readLine();

(int) Math.random()*5+1さらに、6- =(int)(0-.999)* 5 + 1 =(int)(0-4.999)+1 =(int)1-5.999=1-5のDiceRollまたはNextRollを取得することはありません。 。(int) Math.random()*6+1intへのキャストは下向きに丸められるため、代わりに必要になります。

于 2013-03-04T22:35:50.000 に答える