ı basically created a program for a bet game and ı wanted to use math.random method to obtain possible face values.
my question is that math.random is always same value so ı cannot use it repeatedly.
how can ı use math.random method repeatedly. ı dont want to get same value for my dice;
import java.util.Scanner;
public class Lab06d
{
public static double money(double userMoney, int option, double bet )
{
//variable
int dice1;
int dice2;
//codes
dice1 = (int) Math.random() * 6 + 1;
dice2 = (int) Math.random() * 6 + 1;
System.out.println("dice sum: " + dice1 + dice2 );
if(option == 1)
{
if((dice1 + dice2) % 2 == 1)
userMoney = userMoney + ( bet / 2);
else
userMoney = userMoney - ( bet / 4);
}
if(option == 2)
{
if((dice1 + dice2) % 2 == 1)
userMoney = userMoney - ( bet / 4);
else
userMoney = userMoney + ( bet / 2);
}
if(option == 3)
{
if((dice1 == 1 && dice1 == 1) || (dice1 == 6 && dice1 == 6))
userMoney = userMoney + ( bet);
else
userMoney = userMoney - ( bet);
}
return userMoney;
}
public static void main(String[] args)
{
// variables
double userMoney;
int option;
double bet;
//codes
Scanner scan = new Scanner (System.in);
System.out.println("enter your money: ");
userMoney = scan.nextInt();
System.out.println("enter your option 1 for odd 2 for even 3 for extreme: ");
option = scan.nextInt();
System.out.println("enter your bet: ");
bet = scan.nextInt();
System.out.println(money(userMoney, option, bet));
userMoney = money(userMoney, option, bet);
}
}
2 Answers 2
(int) Math.random() * 6 + 1
means the same as
((int) Math.random()) * 6 + 1.
You're first rounding down, then multiplying and adding.
As Math.random() returns as number 0 <= x < 1, it is always casted to 0.
Notice that (int) always rounds down, so (int) 3.999 would become 3 for example, as well as (int)-3.9 would become -4.
Add braces like this:
(int) (Math.random() * 6 + 1)
You can also wrap it into a function like this:
static int throwDice() {
return (int) (Math.random() * 6 + 1);
}
Operators in Java have a specific precedence to them, like multiplication comes before addition in mathematics, unless you use braces. You can look it up here. When in doubt (or to clarify), use braces.
2 Comments
The problem is at the time of initializing dice 1, dice 2. You must remember that you can't pass a primitive type by reference to a method. So you must wrap the COMPLETE DATA, which in this case is Math.random()*6+1 and parse the integer type. So, the code would be
dice1 = (int)(Math.random()*6+1); dice2 = (int)(Math.random()*6+1);
Math.random(), use aRandomobject.