简体   繁体   中英

Testing a random number generator

I am having trouble printing out the first two columns of the results in a table but as I am new to programming I am having issues and wondering where the issue is in my code. The brief states I must create:

  • A parameterless static int method, randInt() , that will return a random integer in the range 0..9 inclusive. This method will include a call to Math.random() .

  • A static void method named randTest that takes a single integer argument, n. This should perform the following actions:

  • Declare an int array of 10 elements named counts. This will be used to record how often each possible value is returned by randInt .

  • Call randInt n times, each time incrementing the count of the element of counts corresponding to the value returned.

  • Print the results to the console in a clear tabular form. The output should look like the following:

在此处输入图片说明

This is my code:

import java.util.Arrays;

public class RandNumGenerator {

    public static int RandInt(){
        double n = Math.random()*10;
        return (int) n;
        }

    public static void randTest(int n){
        int [] counts = new int [10];

        for(int i=0;i<n;i++){
            counts[i] = RandInt();
            System.out.println(counts[i]);
            } 
        }

    public static void main(String[] args) {
        int sampleSize = 1000;      
        System.out.println ("Sample Size: " + sampleSize);
        String[] intArray = new String[] {"Value","Count","Expected","Abs Diff","Percent Diff"};
        System.out.println(Arrays.toString(intArray));
        randTest(10);
        }
    }

public static void randTest(int n){

Question for you to think about: What is the parameter here? Hint: It's not 10... What do you actually want to DO n times?

counts[i] = RandInt();

You really want to create 10 random numbers and store them into the array? Nope. You want to create "sampleSize" numbers and increase the array on the correct position. What would the correct position be?

counts[ correctPosition ] = counts[ correctPosition ] + 1;

...would be more correct, if you can figure out the correctPosition.

Also I would move the output from the main method to randTest() where you have everything together.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM