Reputation: 29
I was trying to make a simple input and do-while
program where I asked for the code to keep repeating if the user didn't input 3.14 but for some reason it isn't running properly. It shows no errors when it I typed it.
Scanner num = new Scanner(System.in);
double pi = num.nextDouble();
do {
System.out.println("What is pi?");
pi = num.nextDouble();
}
while( pi != 3.14);
System.out.println("Yup pi = 3.14");
Upvotes: 1
Views: 77
Reputation: 3297
This is probably related to the fact that comparing floats exactly is bad. Instead, use something like this:
if(Math.abs(pi - (double) 3.14) < epsilon)
Where epsilon
is a number which regulates the precision (Something like 0.001
should be enough in this case). See here for more details: What's wrong with using == to compare floats in Java?
Upvotes: 0
Reputation: 4349
You are reading pi
in twice, one on line 2 and once on line 5. You only need to declare pi
in line 2 and your code will work (see below). Because the body of a do-while loop will always run once you only need one line to ask. You would need to have two lines if you had used only a basic while loop.
Scanner num = new Scanner(System.in);
double pi;
do {
System.out.println("What is pi?");
pi = num.nextDouble();
} while(pi != 3.14);
System.out.println("Yup pi = 3.14");
Upvotes: 1
Reputation: 453
You are asking for input before the loop without notifying the user, take out the first scanner next. like so
Scanner num = new Scanner(System.in);
double pi = 0.0;
do {
System.out.println("What is pi?");
pi = num.nextDouble();
}
while( pi != 3.14);
System.out.println("Yup pi = 3.14");
Upvotes: 1