我需要程序在用戶輸入例如4和6.5時運行,反之亦然。 我有,如果別人運行,只有當其任一或當它試圖在同一時間,我收到了錯誤代碼,這樣運行兩個:當用戶輸入int和double時添加兩個數字
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();
}
}