【发布时间】:2014-02-24 13:53:46
【问题描述】:
我对 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 m/s
您要计算什么?:
您要计算什么?:
}结束
最后,我仍然可以输入 'speed' 并继续执行该程序。我只是想摆脱第二个“你想计算什么”。
任何有关我遇到的问题的意见将不胜感激!!
感谢您非常抽出宝贵时间!
【问题讨论】:
-
请同时考虑 Java 的编码约定。对于命名,您应该使用
input而不是Input和command而不是Command。 -
谢谢伊恩!!我对 Java 的编码约定做了一些研究,你是对的!我没有遵守约定,所以我编辑了我的帖子(和我的程序),并纠正了我的错误。再次感谢!
标签: java while-loop system.out