Quick java help.

Soldato
Joined
31 Oct 2004
Posts
8,691
Location
London
Ok, stuck on a simple piece of java using nested while loops, asking here because I can't take it anymore :p

Right, the problem is: I have to create a program, that 'rolls' a dice until it gets 6, when it gets a six it stops, then prompts the user to enter 0 to stop, and any positive number to continue. If you continue, it 'rolls' again until it gets another 6, then repeats the prompt. If you then enter a 0, which stops the rolling, it then must calculate the average amount of rolls to get 6, then also display the amount of rolls used in calculating the average. Using nested while loops.

What I have so far

Code:
import SE111aClasses.*;
import java.util.*;
public class Tut3_7{
public static void main(String[] args){	

GUI gui = new GUI();
Random rndm = new Random();
int number = rndm.nextInt(6)+1;
int countsix = 0;
int average = 0;
int input = 1;
int counttotal = 0;

while(input!=0)
{
	while(number!=6)
	{
	counttotal++;
	number = rndm.nextInt(6)+1;
	System.out.println(number);
	}
	countsix++;
	input = gui.getInt("Enter 0 for no, above for yes");
}
System.out.println("Average rolls for a six is:" + counttotal/countsix);
System.out.println("Rolls used to calculate the average was:" + counttotal);

}
}

It works for the first roll to 6, then when it reaches the prompt, I enter 1 and it just re-prompts again and again, without re-rolling, only seems to work when i enter 0 and it then calculates it for the first roll to 6 seemingly fine.

Help :(:o
 
Aha, just added:

number = rndm.nextInt(6)+1;

into the while(input!=0) loop, seems to be working fine now, I hope :p. Thanks

Code:
import SE111aClasses.*;
import java.util.*;
public class Tut3_7{
public static void main(String[] args){	

GUI gui = new GUI();
Random rndm = new Random();
int number = rndm.nextInt(6)+1;
int countsix = 0;
int average = 0;
int input = 1;
int counttotal = 0;

while(input!=0)
{
	while(number!=6)
	{
	counttotal++;
	number = rndm.nextInt(6)+1;
	System.out.println(number);
	}
	[COLOR="Red"][b]number = rndm.nextInt(6)+1;[/b][/COLOR]
	countsix++;
	counttotal++;
	input = gui.getInt("Enter 0 for no, above for yes");
}
System.out.println("Average rolls for a six is:" + counttotal/countsix);
System.out.println("Rolls used to calculate the average was:" + counttotal);

}
}

Edit: Loop works, but my counters are screwed :p
 
Last edited:
Back
Top Bottom