import java.util.Scanner;
public class SpeedSound
{
public static void main(String[] args)
{
String input;
double distance;
double time;
final double AIR = 1/1100;
final double WATER = 1/4900;
final double STEEL = 1/16400;
Scanner kyb = new Scanner(System.in);
System.out.print("Enter the corresponding medium:\n ");
System.out.println("Air\n ");
System.out.println("Water\n ");
System.out.println("Steel\n ");
input = kyb.nextLine();
System.out.print("Enter the distance: ");
distance = kyb.nextDouble();
if (distance < 0 || distance > 10000)
System.out.print("Error: ");
switch (input)
{
case "Air":
case "AIR":
time = (distance / 1100);
System.out.println("The total time traveled is " + time + "seconds.");
break;
case "Water":
case "WATER":
time = (distance / 4900);
System.out.println("The total time traveled is " + time + "seconds.");
break;
case "Steel":
case "STEEL":
time = (distance / 16400);
System.out.println("The total time traveled is " + time + "seconds.");
break;
}
}
}
答案 0 :(得分:0)
缩进对java无关紧要,使用{}括号使用一个块,否则只会执行下一个语句。
if (condition) {
// .. lots of
// .. lines of
// .. code
}
答案 1 :(得分:-1)
允许用户输入正确的大写/小写字母(即AIR或Air或Air或aiR等)
因为您需要处理输入的所有lower/upper
个案例版本。在传递给lower case
之前,只需将字符串转换为switch case
,然后只定义小写case
语句而不是多个语句。
intput = input.toLowerCase(); // this is not require if you have converted it earlier
switch (input) {
case "air":
如果用户输入了无效的选择,您的程序应该告诉他们然后退出。
您可以使用if condition
并退出用户:
input = kyb.nextLine().toLowerCase();
if (! (input.equals("air") || input.equals("water") || input.equals("steel")) ) {
System.out.println("Invalid input. Exit");
return;
}
如果距离小于零或大于10000,则显示错误消息并且不进行进一步处理,即退出。
if (distance < 0 || distance > 10000) {
System.out.print("Error: ");
return;
}