我对Java非常陌生(完全是编程)。我相信解决我的问题非常简单,但我无法弄清楚。下面的代码是我的程序的一小部分。但它仍然是可编译的,并且仍然存在相同的问题。我怎样才能使这个陈述(在一个while循环内)不打印两次到控制台?
下面是代码::
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
的距离秒?:
速度为1.0m/S
你想做些什么?:计算
你想什么来计算?:
}结束
最后,我还是可以输入“速度”,并继续与该程序。我只想摆脱第二个'你想要计算什么'。
关于我遇到的问题的任何输入将受到高度赞赏!
非常感谢为您的时间!
请考虑的Java编码约定。命名你应该使用'input'而不是'Input'和'command'而不是'Command'。 –
谢谢恩!我对Java的编码约定做了一些研究,你是对的!我没有遵循惯例,所以我编辑了我的帖子(和我的程序),并纠正了我的错误。再次感谢! – JavaSufferer