我刚刚开始使用Java进行编程,并试图通过用户输入将华氏温度转换为摄氏转换器。以为我有它,但我现在卡住了。我收到以下错误:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
任何帮助都会很棒!
import java.util.*;
class Practicet {
public static void main(String[] args) {
float Fahrenheit = 32;
float Celsius = 0;
Scanner option = new Scanner(System.in);
System.out.println("Do You Want to Enter Fahrenheit or Celsius: ");
int userInput = option.nextInt();
switch (userInput) {
case 0:
System.out.println("Enter temperature in Fahrenheit: ");
Fahrenheit = option.nextInt();
Fahrenheit = (float) ((Fahrenheit - 32) / 1.8000);
System.out.println("Temperature in Celsius = " + Fahrenheit);
System.out.println("Thank You! ");
break;
case 1:
System.out.println("Enter temperature in Celsius: ");
Celsius = option.nextFloat();
Celsius = (float) ((Celsius * 1.8000) + 32);
System.out.println("Temperature in Fahrenheit = " + Celsius);
System.out.println("Thank You! ");
break;
default:
System.out.println("Something went wrong! ");
break;
}
}
}
答案 0 :(得分:0)
问题出在你的switch语句中。收到InputMismatchException
的唯一方法是输入意外值。尝试将int userInput = option.nextInt();
更改为String userInput = option.next();
,并将您的案例从0和1更改为"Fahrenheit"
和"Celsius"