【发布时间】:2020-02-14 10:26:53
【问题描述】:
请任何人帮助我打破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);
}
}
}
}
【问题讨论】:
-
你的
Scanner(实际上什么都没有)永远不会.equals(null)。这根本不可能,因为在null上调用.equals会引发NullPointerException。而且您的Scanner也不等于String。您必须调用nextFoo()方法之一。 -
但是我如何修改它以实现当我按下回车时,它会中断?
-
如果你只是按回车,那么输入将是一个空字符串
""? -
你的意见是什么?
标签: java loops while-loop