Java中温度转换器的优化



所以我很难回到编程上来,我编写了这段代码,将摄氏度转换为华氏度,反之亦然。

它运行良好,但我必须把它缩短。你能用更少的线路让它工作吗?

public static void main(String[] args) {
Double temperature = 0.0;
Double result = 0.0;

String menuChoise = "1. Celsius to Fahrenheit n2. Fahrenheit to Celsius";
int anyChoiseMenu = 3;
System.out.println("Chose a conversion");
System.out.println(menuChoise);
Scanner sc = new Scanner(System.in);
while (true) {
try {
anyChoiseMenu = sc.nextInt();
if (anyChoiseMenu == 1) {
System.out.println("What temperature you wanna convert: ");
temperature = sc.nextDouble();
result = (1.8) * temperature + 32;
System.out.println("Result: " + result + " Fahrenheit");
break;
} else if (anyChoiseMenu == 2) {
System.out.println("What temperature you wanna convert: ");
temperature = sc.nextDouble();
result = ((5 * (temperature - 32.0)) / 9.0);
System.out.println("Result: " + result + " Celsius");
break;
} else {
System.out.println("Wrong number. Try again!");
sc.nextLine();
}
} catch (Exception e) {
System.out.println("Only numbers bro.");
System.out.println(menuChoise);
sc.nextLine();
continue;
}
}
}

您的代码似乎运行得很好。通过一些技巧,如下所示,您可以剪切几行代码。

import java.util.InputMismatchException;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String menuChoice = "nChoose a conversion: n1. Celsius to Fahrenheit n2. Fahrenheit to Celsius";
int menu;
while (true) {
System.out.println(menuChoice);
try {
menu = sc.nextInt();
} catch (InputMismatchException e){
System.out.println("Invalid input, only numbers are allowed!");
sc.nextLine();
continue;
}
if (menu >= 3) {
System.out.println("Wrong number. Try again!");
} else {
System.out.print("What temperature you wanna convert: ");
double temperature = sc.nextDouble();
if (menu == 1) {
temperature = 1.8 * temperature + 32;
} else if (menu == 2) {
temperature = (temperature - 32) / 1.8;
}
String grade = (menu == 1)? "Celsius": "Fahrenheit";
System.out.format("Result: %.2f " + grade + 'n', temperature);
break;
}
}
}
}
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
scan.useLocale(Locale.ENGLISH);
while (true) {
System.out.println("Chose a conversion:");
System.out.println("1. Celsius to Fahrenheit");
System.out.println("2. Fahrenheit to Celsius");
System.out.println("3. Exit");
System.out.print("> ");
int menu = scan.nextInt();
if (menu == 1) {
System.out.print("What temperature you wanna convert: ");
double celsius = scan.nextDouble();
double fahrenheit = 1.8 * celsius + 32;
System.out.format(Locale.ENGLISH, "Result: %.2f Fahrenheitn", fahrenheit);
} else if (menu == 2) {
System.out.println("What temperature you wanna convert: ");
double fahrenheit = scan.nextDouble();
double celsius = (fahrenheit - 32) / 1.8;
System.out.format(Locale.ENGLISH, "Result: %.2f Celsiusn", celsius);
} else if (menu == 3)
break;
else
System.out.println("Wrong number. Try again!");
System.out.println();
}
}

最新更新