import java.lang.Math;
import java.util.Scanner;
public class Temperature {
static int fahrenheit;
static int celsius;
public static int Celsius(int fahrenheit) {
fahrenheit = (int) (5.0 / 9.0 * (fahrenheit - 32));
return fahrenheit;
}
public static int Fahrenheit(int fahrenheit) {
fahrenheit = (int) (9.0 / 5.0 * celsius + 32);
return fahrenheit;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
System.out.println("1. Fahrenheit to Celsius");
System.out.println("2. Celsius to Fahrenheit");
System.out.println("3. Exit");
System.out.println("Choice:");
int choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("Enter temperature: ");
fahrenheit = scan.nextInt();
System.out.println(fahrenheit + " Fahrenheit is " + Celsius(fahrenheit) + " Celsius");
System.out.println("1. Fahrenheit to Celsius");
System.out.println("2. Celsius to Fahrenheit");
System.out.println("3. Exit");
System.out.println("Choice:");
choice = scan.nextInt();
case 2:
System.out.println("Enter temperature: ");
celsius = scan.nextInt();
System.out.println(celsius + " Celsius is " + Fahrenheit(celsius) + " Fahrenheit");
System.out.println("1. Fahrenheit to Celsius");
System.out.println("2. Celsius to Fahrenheit");
System.out.println("3. Exit");
System.out.println("Choice:");
choice = scan.nextInt();
case 3:
break;
}
华氏度到摄氏温度
摄氏到华氏度
出口
选择:
1个
输入温度:
100
100华氏度是37摄氏度
华氏度到摄氏温度
摄氏到华氏度
出口
选择:
2
输入温度:
0
0摄氏度是32华氏度
华氏度到摄氏温度
摄氏到华氏度
出口
选择:
1个
第三次尝试后,无论我输入哪种选择,代码都不再运行。我想要它,只要输入是1或2,它就会继续询问。
最佳答案
您应该有一个菜单方法,例如:
public static void showMenu() {
System.out.println("1. Fahrenheit to Celsius");
System.out.println("2. Celsius to Fahrenheit");
System.out.println("3. Exit");
System.out.println("Choice:");
}
在您的main方法上,可以在
do-while
循环中调用此方法:public static void main(String args[]) {
//Add your Scanner code here, your variables, etc
do {
showMenu();
choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("Enter temperature: ");
fahrenheit = scan.nextInt();
System.out.println(fahrenheit + " Fahrenheit is " + Celsius(fahrenheit) + " Celsius");
break;
case 2:
//Do the same for method 1 but for Celsius
} while (choice != 3);
}
并且,您完成了!