我是 Java 和这个网站的新手,所以请原谅我可能犯的任何错误,我无能为力!
我正在尝试制作一个程序来计算通过不同介质的声速。到目前为止,程序将要求用户输入距离并允许输入,对于媒体也是如此。我创建了几个案例来计算给定媒体的正确工作的答案。
问题是当我尝试创建一个循环来识别媒体输入是否不是可用的 4 个选项之一时。我能够成功地创建一个循环来识别距离输入是否不是数值,并尝试对中等输入使用类似的原则,但要么一直卡在无限循环中,要么在我输入时收到我为错误条目创建的消息正确的选择。我已经尝试过我所学过的基本循环:for、do-while 等,但我被卡住了。任何和所有的建议都非常感谢,非常感谢!
public static void main(String[] args) {
//prompt the user about the purpose of this program
System.out.println(" The purpose of this program is to calculate the speed of sound through several mediums.\n The program user will input a distance in feet followed by a mediums and the program will output the speed in feet per second and miles per hour\n");
//declare variables
Scanner keyboard = new Scanner(System.in);
final double Air = 1126.1;
final double Water = 4603.2;
final double Steel = 20013.3;
final double Earth = 22967.4;
double OneFootPerSecond = .68181818182;
double Distance;
double AirSpeed;
double WaterSpeed;
double SteelSpeed;
double EarthSpeed;
System.out.print(" What is the distance in feet:" );
//ask the user to input variables
while (!keyboard.hasNextDouble()){
System.out.println("Please enter a valid numeric value, try again: ");
keyboard.next();
}
Distance =keyboard.nextDouble();
{
System.out.print("Input the media: Air, Water, Steel, or Earth: ");
String Input = keyboard.next();
Input.toLowerCase();
switch (Input)
{
case "air":
AirSpeed = Distance/Air;
System.out.print("\n \nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through AIR" +"\n");
System.out.printf("%.6f", AirSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond*Air);
System.out.print(" miles per hour.");
System.out.print("\n \nEnter Yes for another calculation, else No: ");
String Another = keyboard.next();
Another.toLowerCase();
break;
case "water":
WaterSpeed = Distance/Water;
System.out.print("\nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through WATER" +"\n");
System.out.printf("%.6f",WaterSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond*Water);
System.out.print(" miles per hour.");
break;
case "steel":
SteelSpeed = Distance/Steel;
System.out.print("\nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through STEEL" +"\n");
System.out.printf("%.6f",SteelSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond*Steel);
System.out.print(" miles per hour.");
break;
case "earth":
EarthSpeed = Distance/Water;
System.out.print("\nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through EARTH" +"\n");
System.out.printf("%.6f",EarthSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond*Earth);
System.out.print(" miles per hour.");
break;