Hi everybody, I really tried to do my assignment but I am lost . Any helping is very helpful , Thanks

Write a program that will generate a set of 50 random integers in the range -20 to + 20. The program
should display the following:
a) The number of positive and negative numbers (treat 0 as positive).
b) The average value of the positive numbers
c) The average value of the negative numbers
d) The largest and smallest number.
e) The average of all the numbers.
You must use a for loop structure for this question along with the Math.random() method to generate
the random numbers.
Hint: Generate numbers in the range of 0-40 and subtract 20

My try is :

public class Assign4A {
public static void main(String[] args){

    // a
    for (int i = 0; i < 50; i++) {
    int random = (int)(Math.random() * (40) + (-20) );
    System.out.print(random + " " );

    }

    //b
    for ( int i = 0; i < 50 ; i++) {
        int random = (int)(Math.random() * (49) + 1 );
        System.out.print( random +  " " +  "\n" );
        }

    int n = 50;
    int sum = runSimulation(n);
    System.out.print(sum  );
}
public static int runSimulation (int n){
    int sum = 0;
    for (int i = 1; i <= n; i++){
        int sim = (int)(Math.random() * (49) + 1 );
        sum += sim;  
    }
    return sum;

 }
}

Recommended Answers

All 7 Replies

You should create a Random class at the beginning of the method, instead of using the Math class. The Random class gives you the option to generate ints directly. nextInt(n) returns an integer in the range 0 (inclusive) and n (exclusive). So, in your case, you would need to use nextInt(41), then adjust for the range -20 through +20. You should also try and do everything in one loop (it is possible to use a seed value to achieve the same random values in mutliple loops, but is inefficient and unnecessary). Then, initialize a few variables, such as:

a) countPos and countNeg
b) sumPos
etc.

Then use those variables after the loop to generate the required results. Give it a try, and let us know how you make out. If you run into any issues, please give an explanation of what isn't working correctly (i.e. what results you're getting vs. what results you expect).

thank you for your reply, I don't know how to create and apply random class because we just learned loops and instructor wants us to use Math.random .Could you solve just one thing between the questions then I can copy with little change to solve others at least how can i find an average 50 random numbers in easiest way

How to find the average of positive numbers?
Loop throughout your array/list, count how many positive and how many negative numbers you have, add them sore them in a variable accordingly, positive in one number, negative in another number, say total_nr_of_positive_numbers for positive numbers, and total_nr_of_negative_numbers for negative numbers, than divide them at your total_number's number:
total_nr_of_positive_numbers/total_numbers
total_nr_of_negative_numbers/total_numbers
When you're looping solve the min/max problem as well. First, you set the first number as being min and max, than at each item from your array/list compare if is greater than your max, and smaller than your min, if so set the fields acordingly, if the number is greater than max, set max to that number, and the same for min, if the number is smaller than your min, set min to that number.
Also for the entire average, when you're looping, store in another variable the sum of all numbers, and than divide it to the total_numbers variable, like sum_of_all_numbers/total_numbers.

i think suggestion given by Lucaci Andrew is worthy.Go trough it.

I agree with Lucaci, but there's a couple things you need to be aware of. First, I wouldn't recommend using Math.random(), but you should of course use what the instructor tells you to. There is one problem however. From the Java API for Math.random():

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

This means that when you mutliply the random value by 40, it will never equal 40. It could be 39.99...; however, since casting to an int simply removes everything after the decimal, this will give you 39. So, to start we need to change it to:

int random = (int)(Math.random() * (41) + (-20) );

And let's get rid of the unnecessary parenthesis:

int random = (int)(Math.random() * 41 - 20);

This isn't the only problem though. Negative numbers cast to an int the same way, but this also means they round in the opposite direction than a positive number. For example, 5.8 rounds to 5 and -5.8 rounds to -5, both towards 0. This becomes a problem for the number -20, since the only way you can get this value is by getting exactly -20 (definately possible, but rare), where as -19 is possible for any value greater than -20 and less than or equal to -19. This creates a problem with the distribution, because not all of the numbers have the same probability. After all of that, there is a simple way to fix it, you simply need to cast it to an int while it is still positive (but after it is adjusted to the range [0,41)). I'll let you handle that by yourself.

My second point is quick. I just wanted to reiterate, use one loop for generating each of the random values, and set all necessary variables to get your results within that one loop.

Thank you for your responses, I write like this , Am I on right track?

        public static void main(String[] args){
            int sumAllNumbers = 0;
            int numPositiveNum = 0;
            int sumPositiveNum = 0;
            int numNegativeNum = 0;
            int sumNegativeNum = 0;
            int biggestNum = 0;
            int smallestNum = 0;
            for (int i = 0; i < 50; i++) {
                int random = (int)(Math.random() * (41) - 20  );

                    if(random >= 0){
                    numPositiveNum++;
                    sumPositiveNum += random;
                 }
                    if (random < 0 ){
                        numNegativeNum++;
                        sumNegativeNum -= random;
                 }


            }

    System.out.println( "There are " + numPositiveNum + " positive numbers" + " and " + numNegativeNum+" negative numbers"  );
    System.out.println("The average value of the positive numbers " + sumPositiveNum / numPositiveNum  );       
          }
        }

int random = (int)(Math.random() * (41) - 20 );

Note quite, reread my post. You have to cast it to an int while the number is still positive (move a parenthesis, hint hint).

if(random >= 0) ...
if(random < 0) ...

While this does work, it is good practice to use an else block in this case, like so:

if(random >= 0) {
    ...
}
else {
    ...
}

sumNegativeNum -= random;

This would give you a positive results (since your negating a negative number). You'd probably want to keep this negative like so:

sumNegativeNum += random;

Other then those few small things, it looks like you're on track.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.