[英]How can I make this statement (within a while-loop) not print out twice to the console?
我是Java的新手,(以及完全编程)。 我确信我的问题的解决方案非常简单,但我无法弄清楚。 下面的代码是我程序的一小部分。 但它仍然可以编译,并且仍然存在同样的问题。
这是代码::
import java.util.Scanner;
public class Practice{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String command = "";
double d; // Distance
double t; // Time
double s; // Speed
System.out.println("Hello, I am the Physics Calculator!!");
while (!command.equals("end")){
System.out.print("What would you like to calculate?: "); // after the first loop, this statement is printed twice to the screen! :(
command = input.nextLine();
System.out.println();
if (command.equals("speed")){
System.out.print("What is the distance in meters?: ");
d = input.nextDouble();
System.out.print("What is the time is seconds?: ");
t = input.nextDouble();
s = d / t;
System.out.println("The Speed is "+ s +" m/s");
System.out.println();
}
} //End of the while-loop
}
}
while循环中的第一行代码是:
System.out.println("What would you like to calculate?: ");
到现在为止还挺好。 当我运行该程序时,它会打印:* 您想要计算什么?:*然后程序按预期继续。
问题是在程序到达while循环结束后,返回到while循环的顶部。 它将打印:
你想要计算什么?:
你想要计算什么?:
我只是想不通为什么它打印两次。
下面是运行程序时收到的确切输出的示例(斜体是控制台的输出, 粗体是我的输入):
开始{
你好,我是物理计算器!!
你想要计算什么?: 速度
以米为单位的距离是多少?: 50
什么时间是秒?: 50
速度为1.0米/秒
你想要计算什么?:
你想要计算什么?:
}结束
最后,我仍然可以输入“速度”并继续使用该程序。 我只是想摆脱第二个'你想要计算什么'。
关于我遇到的问题的任何意见将受到高度赞赏!
非常感谢您的时间!
发生这种情况是因为nextDouble
不使用该数字后面的换行符。 你需要单独做。 目前,下次提示您输入命令时,该换行符(在号码之后)将被消耗。 由于空字符串不是"speed"
,循环会经过一个额外的时间。
添加Input.nextLine();
在t = Input.nextDouble();
这将工作得很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.