gpt4 book ai didi

java计算器随机输出一行

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:40:00 24 4
gpt4 key购买 nike

所以我刚刚开始学习 Java,并从其他一些语言中获得了一点点经验。我试图制作这个基本的计算器并遇到了很多问题,但设法解决了其中的大部分问题。我似乎无法理解的最后一件事是每次我的程序运行一次时随机触发的“这是无效输入”。 “...”指的是不相关的代码。其他一切似乎工作正常。提前致谢!

import java.util.Scanner;
public class Calc {
...
System.out.println("Would you like to use the calculator?(Y/N)");
while(use){
String usage=in.nextLine().toLowerCase();
if(usage.equals("n")){use=false;}
//input
//operations
else if(usage.equals("y")){
...(calculator code)
System.out.println("Continue use? (Y/N)");
}
else {System.out.println("That is not a valid input");}
}
}
}

运行我的代码几次后,我的输出是

Would you like to use the calculator?(Y/N)
Y
Please input an operation: +,-,*,/,%, ^, or root
+
Calculator: Please input your first number.
1
Now enter your second number.
2
Calculating
3.0
Continue use? (Y/N)
That is not a valid input <-- right there is the confusing part, why is that triggered?
Y
Please input an operation: +,-,*,/,%, ^, or root

完整的代码在 pastebin 上,如果你需要的话。 http://pastebin.com/Qee2Hxe3

最佳答案

我检查了完整的代码,就在循环第一次重复之前,调用了 in.nextDouble(),这个方法读取一个 double 但不消耗 行结束,这使得下一个 in.readLine() 立即返回 \n 并且后续测试失败。

一个简单的解决方案是手动消耗行尾:

System.out.println(ans);
System.out.println("Continue use? (Y/N)");
in.nextLine();

关于java计算器随机输出一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17366344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com