为什么我不能按“回车”来中断while循环

roejwanj  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(311)

任何人请帮我打破while循环,我只想结束程序时,用户键入什么,但为什么不能工作?请帮忙,谢谢。

import java.util.Random;
import java.util.Scanner;
import java.lang.Math;

public class Determining_Pi_Experiment {
    public static void main(String[] args) {
        while (true) {
            System.out.println("Press 'enter' to exit, or type an integer number indicating for how many times you " +
                    "want the experiment run: ");
            Scanner input = new Scanner(System.in);
            if(!input.equals(null)) {
                if(input.hasNextInt()) {

                    System.out.println("Processing...");
                    Random rand = new Random();
                    int ExperimentTimes = input.nextInt();
                    double count_success = 0;
                    double Pi = 0;

                    for (int i = 0; i < ExperimentTimes; ++i) {

                        double x = rand.nextDouble();
                        double y = rand.nextDouble();

                        double distance = Math.pow(Math.pow((x - 0.5), 2) + Math.pow((y - 0.5), 2), 0.5);

                        if (distance <= 0.5) {
                            ++count_success;
                        }
                    }
                    Pi = (count_success / ExperimentTimes) * 4;
                    System.out.println("Pi is approximately equal to: " + Pi);
                }
                else {
                    System.out.println("Invalid input.");
                }
            }
            else if(input.equals(null)) {
                System.exit(0);
            }
        }
    }
}
jhkqcmku

jhkqcmku1#

我可以看到你的代码中有很多错误,我会带你去看看。
1) 过于复杂,过于冗长,不需要的检查2)错误使用#equals方法3)不遵循标准命名约定4)对如何构造输入读取循环的一般误解
要对其进行扩展:
1) 尝试简化代码,删除while true循环和else子句(参见第4点),只声明一次变量,在外部删除冗余括号。此外,距离可计算为 Math.hypot(x1-x2, y1-y2) (见此处)
2) 请注意 equals 方法来检查一个对象是否等于另一个对象。如果在您的示例中返回true,则意味着扫描器本身为null(不是它所读取的内容),因此检查无法工作,因为将抛出nullpointerexception(调用null扫描器上的方法)。要检查扫描仪(或任何对象)是否为空,您需要执行以下操作 anyObject == null . 请注意,这与扫描仪输入无关(请参见第4点)。
3) 请正确命名变量(参见此处)。
4) 如果您想继续读取用户输入直到没有更多输入可用,您应该使用scanner#hasnext。如果您希望在输入空字符串时结束,则确实应该检查该字符串是否为空。这与扫描仪为空无关。 someString.isEmpty() 我会帮你的。
伪循环:

while(scanner.hasNextLine() && !((line = scanner.nextLine()).isEmpty()))
 //do something with the input, stored in the line String

//Exits when enter is pressed (or EOF)

相关问题