user2133068
user2133068

Reputation: 37

While loop with if statements does work not but as it is supposed to (Math.random)

My programs goal is to at first generate a random number from 1-6 calling that the 'point' then the user is to keep inputting a key to rey-roll the sopposed 'dice', and if that same number is rolled the user should be prompted with the message from the first if statement

However, whenever the next dice is rolled it never rolls onto the point number, and the first if statement printed line prints out randomly. An answer would be much appreciated on how to fix this?

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();
      }  
    }
  }
}

Upvotes: 1

Views: 264

Answers (2)

ddmps
ddmps

Reputation: 4390

I think what you are looking for to do is to always have to roll the dice, even if it is a match. You can accomplish that by removing the print and input to outside of the else clause, as such:

  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();

Besides, you will never get a DiceRoll or NextRoll that is 6 - (int) Math.random()*5+1 = (int) (0-.999)*5+1 = (int) (0-4.999)+1 = (int) 1-5.999 = 1-5. The cast to int will round downwards, so you will need (int) Math.random()*6+1 instead.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692191

Your loop exit condition is exit == 999. But you never assign any value to exit in the loop. So it loops endlessly.

In addition, you only print the value of the dice when it's not equal to the first roll. And not when it is. So you got the impression that the first message is printed when it shouldn't.

Upvotes: 2

Related Questions