1

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");
  • you don't need `double pi = num.nextDouble();` this since you are using do while – jmj Dec 28 '14 at 23:54
  • For future reference: double arithmetic is inherently imprecise. See http://stackoverflow.com/questions/177506/why-do-i-see-a-double-variable-initialized-to-some-value-like-21-4-as-21-3999996 – PM 77-1 Dec 29 '14 at 00:00
  • Please don't edit your post to say *thanks for the help*. Instead, after the period of grace (15 mins), choose the post that helped you the most to solve your problem and mark it as an answer by clicking on the check below the reputation. – Luiggi Mendoza Dec 29 '14 at 00:03

3 Answers3

1

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");
David Coler
  • 453
  • 3
  • 8
1

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");
carloabelli
  • 4,289
  • 3
  • 43
  • 70
0

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?

Community
  • 1
  • 1
Rick
  • 3,240
  • 2
  • 29
  • 53