简体   繁体   中英

Using a while loop to generate random numbers until a certain number is reached

I'm learning about while loops. In my Java class currently I'm trying to modify a program to use a basic while loop to generate random numbers until a certain number is reached. In this particular case I want it to print until it goes below .0001. I've gotten myself confused while trying to do it and am not getting any output. I'm looking for any hints or tips that anyone might have to help me along with this or help further my understanding. Here's what I have for code so far:

import java.util.Random;
public class RandomNumbers {

    public static void main(String[] args) {
        Random rand = new Random();

        double val = 1;

        while(val < .0001){
            val = rand.nextDouble();
            System.out.println(val);
        }
    }
}

The while conditions says:

"While x condition is true, do this"

In this case, you have val=1 that is grather then 0.0001. So the while gets never executed. So setting while(val>0.001) , means:

"While my val is grater then 0.001, print it out. If is less then 0.001, return"

In code:

import java.util.Random;
public class RandomNumbers {

public static void main(String[] args) {
    Random rand = new Random();

    double val=1;

    while(val>.0001){
        val=rand.nextDouble();
        System.out.println(val);

    }
}

}

Simple logic error. Based on your current code the while loop will never run because val<.0001 will always be false ( 1 > .0001 ). You need to modify that line to this:

while(val > 0.0001){

Also it's usually better to write decimals with a 0 in front of the . for improved readability.

Your error is just simple to correct. You didn't tell your code to increase or decrease (++ or --) you should set your variable to increase or decrease base in what you want it to do.

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