[英]Why can't I break my while loop by press 'enter'
任何人都请帮助我中断 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);
}
}
}
}
我可以在您的代码中看到许多错误,我将引导您完成这些错误。
1) 过于复杂、过于冗长、不需要的检查 2) 误用#equals 方法 3) 不遵循标准命名约定 4) 对如何构建输入读取循环的普遍误解
扩展它们:
1)尝试简化您的代码,删除 while true 循环和 else 子句(参见第 4 点),仅在外部声明一次变量,删除多余的括号。 此外,距离可以计算为Math.hypot(x1-x2, y1-y2)
(参见此处)
2)请注意,应使用equals
方法检查 object 是否等于另一个 object。如果在您的示例中返回 true,则意味着扫描仪本身是 null(不是它正在读取的内容),因此检查无法工作,因为会抛出 NullPointerException(调用 null 扫描器上的方法)。 要检查扫描仪(或任何对象)是否为 null,您需要执行anyObject == null
。 请注意,这与扫描仪输入无关(参见第 4 点)。
3)请正确命名变量(见此处)。
4)如果你想继续阅读用户输入直到没有更多输入可用,你应该使用Scanner#hasNext 。 如果您想在输入空字符串时结束,您确实应该检查该字符串是否为空。 这与扫描仪 null 无关。someString.isEmpty 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.