简体   繁体   English

在我的do-while循环之前获取输入,但是无法正确响应该输入

[英]Taking input prior to my do-while loop but it doesn't respond correctly to that input

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. 我试图制作一个简单的输入和do-while程序,在该程序中,如果用户未输入3.14,但由于某种原因,它无法正常运行,我要求代码保持重复。 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 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");

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). 您正在读pi两次,在第2行读一次,在第5行读一次。您只需要在第2行声明pi ,您的代码就可以使用(请参见下文)。 Because the body of a do-while loop will always run once you only need one line to ask. 因为do-while循环的主体将始终运行,只需要一行即可询问。 You would need to have two lines if you had used only a basic while loop. 如果只使用了基本的while循环,则需要两行。

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");

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). epsilon是控制精度的数字(在这种情况下, 0.001东西就足够了)。 See here for more details: What's wrong with using == to compare floats in Java? 有关更多详细信息,请参见此处: 在Java中使用==比较浮点数有什么问题?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM