当用户输入例如 4 和 6.5 时,我需要运行该程序,反之亦然。 我仅在其任一或或时运行 if else,当它尝试同时运行两者时,我收到如下错误代码:
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)
at class2.AddTwoNumbers.main(AddTwoNumbers.java:28)
任何帮助将不胜感激
public class AddTwoNumbers {
public static void main(String[] args) {
Scanner inputSource = new Scanner(System.in);
Scanner runAgain = new Scanner(System.in);
int input1, input2, result;
double input3, input4, result2;
String answer = null;
do {
System.out.println("Please enter two numbers: ");
if(inputSource.hasNextInt()) {
input1 = inputSource.nextInt();
input2 = inputSource.nextInt();
result = input1 + input2;
System.out.println("The sum of " + input1 + " and " + input2 + " is " + result);
} else if (!inputSource.hasNextInt()){
input3 = inputSource.nextDouble();
input4 = inputSource.nextDouble();
result2 = input3 + input4;
System.out.println("The sum of " + input3 + " and " + input4 + " is " + result2);
} else if (inputSource.hasNextInt() || inputSource.hasNextDouble()){
input1 = inputSource.nextInt();
input3 = inputSource.nextDouble();
result2 = input1 + input3;
System.out.println("The sum of " + input1 + " and " + input3 + " is " + result2);
}
System.out.println("Do you want to run this again? Enter Y for Yes or N for No: ");
answer = runAgain.next();
} while (answer != "N");
inputSource.close();
}
}
最佳答案
在这种情况下,使用 double number = Double.parseDouble(inputSource.nextLine()); 读取输入更有意义。这适用于 int
和 double
输入。
您的代码变得如此简单:
double input1 = Double.parseDouble(inputSource.nextLine());
double input2 = Double.parseDouble(inputSource.nextLine());
double result = input1 + input2;
除此之外,将 while (answer != "N");
更改为 while (!answer.equals("N"));
。
关于java - 当用户可以输入 int 和 double 时添加两个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32558143/