【发布时间】:2020-10-03 07:56:42
【问题描述】:
您好,我编写了一个程序,使用开关将一种温度从一种温度转换为另一种温度。
默认不起作用:
当我输入一个有效选项时,它工作得很好,但是当我选择无效选项时,它会默认输出以下行:您输入无效选项,请再次选择并停止工作,不允许我这样做选择另一个选项。
我之前测试它时,默认允许我选择另一个选项。
import java.util.Scanner;
public class Tempature {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
double fahrenheit,celcius,kelvin;
System.out.println("Choose type of temperature:\nf. Fahrenheit\nc. Celcius\nk. Kelvin");
String word = scan.nextLine();
switch(word){
case "f": System.out.println("Enter Fahrenheit temperature: ");
fahrenheit=scan.nextDouble();
celcius = (fahrenheit-32) * 5/9;
kelvin = (fahrenheit + 459.67) * 5/9;
System.out.println("" + celcius + " C");
System.out.println("" + fahrenheit + " F");
System.out.println("" + kelvin + " K");
break;
case "c": System.out.println("Enter the Celcius temperature: ");
celcius=scan.nextDouble();
fahrenheit = (celcius*9)/5 + 32;
kelvin = celcius + 273.15;
System.out.println("" + celcius + " C");
System.out.println("" + fahrenheit + " F");
System.out.println("" + kelvin + " K");
break;
case "k": System.out.println("Enter the Kelvin temperature: ");
kelvin=scan.nextDouble();
fahrenheit = 1.8*(kelvin - 273.15) + 32;
celcius = kelvin - 273.15;
System.out.println("" + celcius + " C");
System.out.println("" + fahrenheit + " F");
System.out.println("" + kelvin + " K");
break;
default: System.out.println("You enter invalid choice, please choose again");
}
scan.close();
}
}
【问题讨论】:
-
你所说的“停止工作”是什么意思,你希望它在处理完默认情况后会做什么?输入有效选项后会发生什么,它会继续工作吗?
-
当我输入一个有效选项时它继续正常工作,早先写测试它默认选项允许我再次选择另一个选项,这次它不允许我选择只是停止程序。
-
您的代码中没有任何内容允许用户输入多个选项,当您选择 c/f/k 时,它允许输入一个值然后程序结束。正如所写,您的编程工作正常。为了允许用户选择第二个....n 选项,需要有某种循环。也许在接受用户输入的 Java 命令行应用程序上进行谷歌搜索。
-
这正是您为它编写的内容。当输入无效字符时,它将打印您提到的语句并退出。如果您希望它一直提示您,直到您输入有效字符,您可以尝试使用 do-while 循环。
-
附带说明,您可能希望将重复/重复的代码移动到方法中。
标签: java switch-statement case java.util.scanner default