Click to See Complete Forum and Search --> : Math.Random()......again.....


fukchai2000
01-26-2005, 05:54 PM
I've posted b4...and terribly sorry about the last post...hope you can help me out again.....:(

ok...here what i trying to do: (sorry for didn't post it in the begining)

public class roll{

public static void main(String args[]){
int face;

for (int i=0;i<6;i++)
{
face = (int)(Math.random()*6)+1;
System.out.println(face);
}
}

this code will print out a random number from 1 - 6 (probably same number will be printed out twice......)

what i actually want is .....make sure that each number only being printed once.....hope you guys can help me out

thanks a lot.........

PittsburghRed
01-26-2005, 08:11 PM
Why are you generating random integers if you want to print out each integer from 1 to 6 with no repeats?

buntine
01-26-2005, 08:52 PM
If you want only distinct numbers to show, most of the time there will be less than 6 numbers as duplicates will be skipped.

The ArrayList object may be helpful.

public class Roll
{
private ArrayList rolls;
public static void main(String args[])
{
int face;
rolls = new ArrayList();

for (int i=0;i<6;i++)
{
face = (int)(Math.random()*6)+1;
addRoll(face);
}
System.out.println(generateRollData());
}

private void addRoll(int roll)
{
Integer intRoll = (Integer)roll;
if (!rolls.contains(intRoll))
rolls.add(intRoll);
}

private String generateRollData()
{
String strRolls = new String("");
for (int i=0; i<rolls.length(); i++)
{
Integer intRoll = (Integer)rolls.get(i);
strRolls += intRoll.toString();
if (i<(rolls.length()-1))
strRolls += ", ";
}
return strRolls;
}
}

Have a play around with that.

By the way, PittsburghRed, the idea is to roll the dice six times and get no repeats. eg 1, 2, 4, 6 (3 and 5 were not rolled)

Regards,
Andrew Buntine.

p.s Its convention to start class names in upper-case. Roll instead of roll.

fukchai2000
01-27-2005, 08:25 PM
thanks....

is there any other ways beside using the array??..

PittsburghRed
01-27-2005, 08:43 PM
aha! He wants to roll the dice 6 times and delete the repeats? Trying to find a roll where all faces come up exactly once?