我想編程一個基本的計算器,它需要兩個數字並添加它們。首先假定輸入的數字是整數,如果不是,它會拋出並捕獲一個異常,並假定輸入的輸入是雙精度。該程序工作正常,除非第一個輸入的數字是整數,第二個是雙倍,它只是掛起,什麼都不做。掃描儀不會記得以前輸入的整數
/* Reads two numbers. Assuming the entered input is integer, Adds
* the numbers and prints out the result If not integer, throws an
* InputMismatchException.*/
Scanner inputSource = new Scanner(System.in);
try
{
Integer input1, input2, result;
input1 = inputSource.nextInt();
input2 = inputSource.nextInt();
result = input1 + input2;
System.out.println("The Sum of " + input1 + " and " + input2 + " is " + result);
}
catch (java.util.InputMismatchException e)
{
double input1, input2, result;
input1 = inputSource.nextDouble();
input2 = inputSource.nextDouble();
result = input1 + input2;
System.out.println("The Sum of " + input1 + " and " + input2 + " is " + result);
}
「掃描儀不記得先前輸入的整數」掃描儀不應該記住任何**。 –
當第二個輸入是一個Integer時,它會拋出一個異常並等待你輸入兩個雙精度值。等待輸入不是「掛起」。 – azurefrog
@azurfrog你是對的我剛剛測試過。但是,如何將之前輸入的整數作爲一個雙精度? 例如:如果我輸入7和8.5 –