Skip to main content

a small program and a small problem

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
Posted by shehio on November 25, 2011 at 9:16 AM PST

package rolling.dice;

public class RollingDice {

public static double turns(int sum)

{

int flag = 0 ;

double turns = 0 ;

while(flag!=1)

{

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

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

if ( (dice1+dice2)==sum )

flag = 1 ;

turns++;

}

System.out.println(turns);

return turns;

}

public static void main(String[] args) {

int i = 1;

double average = 0 ;

while(i<13)

{

average = 0;

for(int j = 0 ; j < 1000 ; j++) // try reducing j to 5 for example it wont work either.

{

average += turns(i)/1000;

}

System.out.println("The average of: " + i + " is: " + average ) ; // nothing happens ...disappointing :S

i++;

}

}

}

Comments

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Re: a small program and a small problem

Hi there is infinite loop in the code

while(flag!=1) remains true forever means the loop still looping and looping

it should be flags++; instead of turns++; or something like that

while(flag!=1)

{

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

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

if ( (dice1+dice2)==sum )
flag = 1 ;

turns++;

}