Results 1 to 3 of 3

Thread: Help with Loop

  1. #1
    PsychoNaut is offline Member
    Join Date
    Oct 2010
    Posts
    4
    Rep Power
    0

    Default 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 04:53 AM.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    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.

  3. #3
    PsychoNaut is offline Member
    Join Date
    Oct 2010
    Posts
    4
    Rep Power
    0

Similar Threads

  1. Replies: 5
    Last Post: 04-30-2010, 06:05 PM
  2. do while loop?
    By shroomiin in forum New To Java
    Replies: 2
    Last Post: 11-13-2009, 11:32 AM
  3. For Loop
    By YiBoog in forum New To Java
    Replies: 6
    Last Post: 11-11-2009, 08:53 PM
  4. while-loop stopping on first loop
    By davester in forum New To Java
    Replies: 6
    Last Post: 06-26-2009, 09:46 PM
  5. while loop
    By Unknown1369 in forum New To Java
    Replies: 5
    Last Post: 07-08-2008, 11:15 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •