3

Right now i am using

 int die = (int)(6.0 * Math.random()) + 1;

This does not work for the loop i am trying to create. This is the method i am using.

public void computerRoll()
{ 

 do { roll();
      System.out.println("Roll:"+ die);
      computerScore += die;
     } while (computerScore <= 20 && die >=2 && die <=6 );
     if (computerScore >=20)
        computerHold();

     if (die == 1)
        switchTurn();

 }

The roll() method just simply has the previous line of code in it, "int die = (int)(6.0 * Math.random()) + 1;" i have tried moving it around or even making a place holder for it but if i execute the method and the number is not a 1, it just prints that number until it reaches twenty. I am trying to create a "dice" that will make a NEW number each time it is used.

Renuz
  • 1,587
  • 7
  • 21
  • 34
  • The real problem is *likely* that you are shadowing `die` inside `roll()` and are thus only assigning a variable to the *local variable* named "die", not the *member variable* with the same name. See Jaco Van Niekerks (and Jons) answer for a cleaner solution that avoids this issue entirely. –  Dec 07 '11 at 04:52

1 Answers1

4

It seems like your roll-method is not handled as a function. You need to return the value generated by your roll() function.

Try this:

int roll() {
    return (int)(6.0 * Math.random()) + 1;
}

and then:

public void computerRoll() { 

    do { 
        int die = roll();
        System.out.println("Roll:"+ die);
        computerScore += die;
     } while (computerScore <= 20 && die >=2 && die <=6 );
     if (computerScore >=20)
         computerHold();

     if (die == 1)
         switchTurn();

 }
Jaco Van Niekerk
  • 4,180
  • 2
  • 21
  • 48
  • Thanks, that makes it work. So the only problem i had was not returning the value? can you explain that more in depth on why it did work when i put a return statement, but not when i did not. – Renuz Dec 07 '11 at 05:08
  • That you'll need to google. A return statements returns a value from a function. By calling "int die = roll()" you assign the value that function roll() returned to the variable die. – Jaco Van Niekerk Dec 08 '11 at 15:41