Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Could someone check my code out for me? (I'm a total newb)

  1. #1
    Junior Member
    Join Date
    Apr 2014
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Could someone check my code out for me? (I'm a total newb)

    I apologize for my newbiness, I'm in basic java right now and I have a project due tomorrow. I have the code written down but it does not match/add up to the output
    Could anyone help fix it up?

    There are 2 class files.

    CoinToss.java

    import java.util.Scanner;
     
    public class CoinToss {
     
    private static final int MIN_HEADS = 0;   // minimum number of heads per set
     
    /**
    * main method:
    * ask the user how many sets of coin flips and how many flips per set
    * count occurances of heads in user specified number of sets of coin flips
    * draw a horizontal and vertical histogram of the number of heads
    */
    public static void main(String[] args) {
     
    // set up to get user input
    Scanner scan = new Scanner(System.in);
     
    // ask user for the number of sets of coin flips
    System.out.println("How many sets of coin flips do you want?");
    int nSets = scan.nextInt();
     
    // ask user for the number of coin flips per set 
    System.out.println("How many coin flips per set do you want?");
    int nFlips = scan.nextInt();
     
    // maximum number of heads that can occur is number of flips
    int maxHeads = nFlips;      
     
    // calculate maximum length of histogram bars based on number of flips per set
    // based on finding the number of combinations for half heads / half tails
    //                n!
    // formula is -----------  with r = n/2
    //             r! (n-r)!
     
    int maxLength = factorial (nFlips) / 
                    (factorial (nFlips / 2) * factorial (nFlips - nFlips / 2));
     
    // instantiate a coin object named myCoin
    Coin myCoin = new Coin();
     
    // step 1:
    // declare an int array named "counts" to count coin flip occurences
    // make its size one larger than maxHeads
    int counts[] = new int [maxHeads + 1];
     
     
    // step 2:
    // initialize all of the values in the array to 0
    for(int x = 0; x < counts.length; x++) 
    {
      counts[x] = 0;
    }
     
     
    // step 3:
    // instantiate an array of Coin objects of size nFlips and
    // instantiate a Coin object in each element of the array
    Coin[] coinArray = new Coin[nFlips];
    for(int x = 0; x < coinArray.length; x++) 
    {
      coinArray[x] = new Coin();
    }
     
     
     
    // step 4:
    // flip each coin in the array once per set nSets times and
    // count the number of heads in each set (heads = 1, tails = 0)
     for (int x = 0; x < nSets; x++)
    {
      int sum = 0;
      for (int i = 0; i <nFlips; i++)
      {
        sum = sum +(myCoin.flip()? 1:0);
      }
    }
     
     
    // step 5:
    // print out the estimated probabilities of all heads and all tails
    System.out.println((float) counts [MIN_HEADS] / nSets);
     
     
    // step 6:
    // instantiate an object of the Histogram class with 
    // the array to be drawn, the indices of valid data,
    // and the maximum length of the bars in the histogram
    //
    // call its two draw methods to draw the two histograms
    int maxCount = 0;
    for (int x = MIN_HEADS; x < maxHeads +1; x++)
    {
      if(maxCount <= counts [x])
      {
        maxCount = counts [x];
      }
      break;
    }
     
    }
     
    // function to calculate factorial of n
    private static int factorial(int n)
    {
    int factorial = 1;
     
    // write the code for a loop to calculate factorial of n here
    for(int x = 1; x <= n; x++) 
    {
      factorial *= x;
    }
     
    return factorial;
    }
    } /* 201420 */

    Histogram.java
    public class Histogram 
    {
    private int [] values;
    private int minIndex;
    private int maxIndex;
    private int maxLength;
     
    /** constructor for histogram drawing class
    * @param values the array of integer values to draw
    * @param minIndex the lowest index in the array for the range to draw
    * @param maxIndex the highest index in the array for the range to draw
    * @param maxLength the length of line to draw for the largest value
    */
     
    public Histogram(int [] values, int minIndex, int maxIndex, int maxLength) 
    {
    // initialize the values of the instance variables from the constructor parameters
    this.values = new int [maxIndex + 1];   // allocate memory for a copy of the values array
    this.minIndex = minIndex;
    this.maxIndex = maxIndex;
    this.maxLength = maxLength;
     
    // step 7: 
    // find largest number in values array for scaling length of bars
    int MaxValue = values[0];
    for(int x=minIndex; x<=maxIndex; x++)
    {
      if (values[x] > MaxValue)
        MaxValue = values[x];
    }
     
     
     
    // step 8:
    // copy data from values array to this.values array while scaling to maximum length of bars
    System.arraycopy(values,0,this.values,0,values.length);
     
     
    }
     
    /** draw a horizontal bar graph
    */
     
    public void drawHor()
    {
    // step 8:
    // draw horizontal bar graph (one line per roll value)
    for (int i = 1; i<values.length; i++)
      System.out.print("Value " + i + ":" + "\t" + values[i]);
      System.out.println("*");
    }
     
     
    /** draw a vertical bar graph
    */
     
    public void drawVer()
    {
     
    // step 10:
    // draw vertical bar graph (one column per roll value)
    for (int i = 1; i<values.length; i++)
      System.out.print("Value " + i + ":" + "\t" + values[i]);
      System.out.println("*");
     
     
    }
    }/*201420*/

    And this is what the output is supposed to be

    > java Histogram
    How many sets of coin flips do you want?
    1000
    How many coin flips per set do you want?
    6
    Estimated probabilities for:
    All Heads:         0.015
    All Tails:         0.011
     
    Heads Count 0:      * 1
    Heads Count 1:      ****** 6
    Heads Count 2:      *************** 15
    Heads Count 3:      ******************** 20
    Heads Count 4:      **************** 16
    Heads Count 5:      ****** 6
    Heads Count 6:      * 1
     
    Count 20          *         
    Count 19          *         
    Count 18          *         
    Count 17          *         
    Count 16          *  *      
    Count 15       *  *  *      
    Count 14       *  *  *      
    Count 13       *  *  *      
    Count 12       *  *  *      
    Count 11       *  *  *      
    Count 10       *  *  *      
    Count  9       *  *  *      
    Count  8       *  *  *      
    Count  7       *  *  *      
    Count  6    *  *  *  *  *   
    Count  5    *  *  *  *  *   
    Count  4    *  *  *  *  *   
    Count  3    *  *  *  *  *   
    Count  2    *  *  *  *  *   
    Count  1 *  *  *  *  *  *  *
             0  1  2  3  4  5  6
    >

    This is my output when I run it

    > run CoinToss
    How many sets of coin flips do you want?
     [1000]
    How many coin flips per set do you want?
     [6]
    0.0
    >


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Could someone check my code out for me? (I'm a total newb)

    A great first post! Thanks for taking the time to post your code correctly, give appropriate details, example runs, etc. Very nice!

    And your code is well commented! The only thing a little off is that your code indentation is not right, but that's manageable.

    As I read through your comments and compare to your code's results, it appears there's a breakdown around step 3 or 4. Are you stuck at or confused about a certain step?

    Also, explain "sets of coin flips and how many flips per set" to me. In the sample run, 1,000 coin flips per 6 sets would be 6,000 flips, wouldn't it? I assume that must be scaled to the desired size of the histogram . . .

    Can you post the assignment? That might help.

  3. #3
    Junior Member
    Join Date
    Apr 2014
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Could someone check my code out for me? (I'm a total newb)

    Thank's for your input.

    A friend also helped me out with this assignment, so that's what he posted. Basically you could say i'm stuck

    I believe it should be scaled, but that's where I have doubts in my code.

    Here's the assignment.
    1.  Declare an integer array named “counts” with a size equal to maxHeads + 1.  Each integer element in this array will contain the count of occurrences of that number of heads in a set of coin flips.  For example, if 4 was the number of heads in 26 sets of coin flips, the array element “counts[4]” will contain the integer value 26.  The lowest element in the array that you will use is “counts[MIN_HEADS]” and the highest element in the array that you will use is “counts[maxHeads]”.    
     
    2. Execute a loop to initialize the value of all elements in the array from MIN_HEADS up through maxHeads to 0.  If we are going to start counting the number of times a particular number of heads occurs, we want to start all of our counts at zero.
     
    3 Instantiate another array of Coin objects of size nFlips and instantiate a Coin object in each element of this array
     
    4. Using the value nSets (the number of sets of flips) and nFlips (the number of coin flips per set) from the user, execute a loop nSets times. Each time through this outer loop, your code starts with sum equal to zero and loops for nFlips times - calling the flip method of each Coin object in the array and adding the returned face value to the sum. After the inner loop completes, the outer loop uses the sum calculated by the inner loop as an array index, and increments the value of that element in the counts array.
     
    5.  Now calculate the frequency of occurrence of all heads and all tails.  The counts[MIN_HEADS] array element contains a count of the number of times there were no heads.  Divide that number by the number of sets (nSets) to get the frequency.  Do the same for the array element that contains the count of the number of times there were all heads.  You should cast your data from integer to float or double to perform this calculation since the frequency values will all be between 0 and 1.  (If you do the division in integer arithmetic, all answers will come out to be 0 due to the truncation of the fractional parts.)
     
    It’s nice to see values for these two frequencies, but it would also be nice to display the data visibly to allow a user to observe the pattern of the frequencies for the number of heads in a set. 
     
    6.  At this point, your CoinToss code instantiates an object of Histogram class and passes the array of counts, the limits of the indices to draw, and the maximum length of the bars desired as parameters to the Histogram constructor method.  It then calls the Histogram object’s two draw methods.
     
    You must write the rest of the code in the Histogram constructor and the two Histogram class draw methods.  Note that this class has nothing to do with coins or coin tossing.  The draw methods can draw histograms for any kind of data values that are passed to it in its parameter list.  Hence, we use “neutral” names for all variables in the Histogram methods – not names like “flips” that imply any such activity related to the game of Coin Toss. The histogram draw method needs to do the following steps in the following order (where indicated by the comments in the code itself):
     
    In the Histogram constructor method, we need to initialize the instance variables from the supplied parameters.  This code has been provided for you.  You should study it and what it is doing to understand it.  You need to write the rest of code for the constructor in steps 6 and 7.
     
    7. and 8. We may have very large values in the values array supplied as a parameter.  Since we want to limit the size of the histogram bar graph to maxLength, we need to scale the data in the values array when we copy it into the instance copy of the data in the array.  This consists of two loops.  The first loop finds the largest value in the values array. (Declare, initialize, and use a variable named something like “maxValue”).  The second loop multiplies each value in the values array by the max length we want for bars (maxLength) and divides by the largest value found (“maxValue”).  Remember the limitations of multiplication and division for integer variables.  You may need to cast the integer values to double for the calculation and cast the result back to integer to update the value in each counts array element with good “resolution”.  You can also get good resolution by performing integer multiplications and divisions in the correct order.  See if you can do that as it will have better run time performance.
     
    9.  In the drawHor method, your code must draw a horizontal bar graph of the data in the values array.  (See Sample Output)  This will require two nested loops.  The outer loop will be a scan through each element of the values array and the inner loop will print an asterisk from 1 through the value in the outer loop element of the values array.  Print the values array integer at the end of each bar of asterisks.
     
    10.  In the drawVer method, your code must draw a vertical bar graph of the data in the values array.  (See Sample Output)  This is a little trickier than the horizontal bar graph.  You still need two nested loops.  The outer loop will count down through all the values from maxLength to 1 to print each line.  The inner loop will print a piece of each line for each value (index into the values array).  If the count for the value is greater than or equal to the decreasing count of the outer loop, print an asterisk with a space on either side of it.  If the count for the value is not greater than or equal to the value of the outer loop count, print an equivalent number of spaces to maintain the column alignment but not show the “bar” in this column.

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Could someone check my code out for me? (I'm a total newb)

    This statement is perplexing (or just plain wrong):

    "Each integer element in this array will contain the count of occurrences of that number of heads in a set of coin flips. For example, if 4 was the number of heads in 26 sets of coin flips, the array element “counts[4]” will contain the integer value 26."

    In simpler language, it says that the elements of the array counts[] contains the number of heads resulting from a certain number of flips. I would interpret that as counts[26] = 4. I would question that statement or at least point out that it's confusing (or wrong).

    Even so, your code for step 4 is incomplete. Reread the instructions. Your outer loop is missing a step.

Similar Threads

  1. Replies: 7
    Last Post: May 8th, 2013, 02:33 PM
  2. Java Newb...forum newb also
    By ElTucan831 in forum Member Introductions
    Replies: 2
    Last Post: December 22nd, 2012, 06:08 PM
  3. Replies: 1
    Last Post: November 2nd, 2012, 04:16 PM
  4. code to refresh and check the code of a webpage..
    By vaggelis in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 7th, 2012, 07:43 AM
  5. [SOLVED] What's wrong with my code?? (Total beginner)
    By TheProf in forum What's Wrong With My Code?
    Replies: 10
    Last Post: January 6th, 2012, 02:41 PM