Reputation: 3
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);
}
}
}
Upvotes: 0
Views: 4540
Reputation: 1
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.
Upvotes: 0
Reputation: 4349
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.
Upvotes: 1
Reputation: 2775
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);
}
}
}
Upvotes: 3