Results 1 to 3 of 3
Thread: Help with Loop
- 10-14-2010, 03:37 AM #1
Member
- Join Date
- Oct 2010
- Posts
- 4
- Rep Power
- 0
Help with Loop
Hello, I really could use some help with this mini-assignment, im halfway through the semester with all A's on my projects(no help), but this one really makes me feel dumb :(
"Write a class TwoDice with a static method rollTimes(int n) that returns the average(as a double) of the points when two dice are rolled independently n times. You do that by using the expression above twice and add the results into an "accumulator" variable. At the end divide the accumulated sum by n but watch out for the fine distinction between integer
and normal division."
(int)(Math.random()*6)+1 = 1, 6 sided dice roll
Heres the code:
public class TwoDice
{
public static double rollTimes(int n)
{
int diceRoll1=(int)(Math.random()*6) + 1;
int diceRoll2=(int)(Math.random()*6) + 1;
int add= diceRoll1+diceRoll2;
int sum=0;
for(int i=n; i>=0; i--)
{
sum=add;
sum=sum+add;
}
double div = (double)(sum/n);
return div;
}
}
It outputs zero repeatedly..
I know there must be something wrong with my loop logic.. Can I pass the variable input n through the loop?
Any hints is appreciated.Last edited by PsychoNaut; 10-14-2010 at 03:53 AM.
-
You create a pair of random numbers once and once only rather than each time the dice is rolled, and the logic in the for loop is farked up beyond belief (sorry for the bluntness). Solution: 1) Get two random numbers with each roll and 2) figure out your program logic before writing code. The logic isn't hard, and if you figure it out on paper before trying to code it, it will come to you. Seriously, it will.
- 10-14-2010, 06:01 AM #3
Member
- Join Date
- Oct 2010
- Posts
- 4
- Rep Power
- 0
Similar Threads
-
How can I rewrite the following while loop using a for loop?
By gt11990 in forum New To JavaReplies: 5Last Post: 04-30-2010, 05:05 PM -
do while loop?
By shroomiin in forum New To JavaReplies: 2Last Post: 11-13-2009, 10:32 AM -
For Loop
By YiBoog in forum New To JavaReplies: 6Last Post: 11-11-2009, 07:53 PM -
while-loop stopping on first loop
By davester in forum New To JavaReplies: 6Last Post: 06-26-2009, 08:46 PM -
while loop
By Unknown1369 in forum New To JavaReplies: 5Last Post: 07-08-2008, 10:15 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks