vendredi 19 mars 2021

Error using "for" to generate 100 random numbers in java eclipse and compare them to the user value

I am brand new to java and I have this problem that I always get 0 random numbers greater than the user value, and I should be getting a different amount of random numbers greater than the value every time I run the program

package chapterfinal;
import java.util.Scanner;

public class finalf {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner input = new Scanner (System.in);
    int greaterOrequal = 0;
    int count = 0;
    final int finalcount = 100;
    System.out.println("Enter a value between 30 and 70: ");
    int value = input.nextInt();
    
    while (value > 70 || value < 30) {
        System.out.println("Please try to enter a value between 30 and 70: ");
        value = input.nextInt();
        
    }
    
    for (count = 0; count < finalcount; count++) {
        int random = (int) Math.random() * 100;
        if (random >= value)
                greaterOrequal++;
    }
        System.out.println("There are " + greaterOrequal + " random numbers greater than " + value);
            
} }

the "while" code is to prompt the user to reenter a value between 30-70 in case the user enters something out of that range.

the "for" code is to generate 100 random numbers and analyze how many are greater than the value that the user entered.

And finally just print the result of how many randoms were greater than the value and print the value that the user entered

I know is a really simple code, I can't find what is wrong with it!

This is the result that I get:

Enter a value between 30 and 70: 
80
Please try to enter a value between 30 and 70: 
50
There are 0 random numbers greater than 50

And it should be something like:

Enter a value between 30 and 70:
25
Please try to enter a value between 30 and 70:
50
There are 51 random numbers greater than 50

I should get a different amount of random numbers greater than the user value every time I run the program.

I hope any of you guys can help me

Please any help is appreciated!!




Aucun commentaire:

Enregistrer un commentaire