我正在編寫一個簡單的程序,允許用戶輸入兩個單獨的雙精度進行英尺和英尺測量。該程序旨在獲取這些值並將其轉換爲釐米並輸出。另外我要包括兩個例外:一個確保數值是正值而不是負值(我已經完成了這個)和另一個確保輸入的值是一個double值而不是一個字符串值(我正在使用這個值很難與)。因此,如果用戶輸入一個輸入...例如'Bill'而不是一個數字,它將顯示一條錯誤消息並要求用戶重新輸入輸入值。Java:使用Try/Catch Exception檢查用戶輸入是否爲雙精度
看來也許我最好將用戶輸入作爲一個字符串來收集(而不是像我目前所做的那樣加倍),我將其轉換爲雙精度並將它們作爲雙精度返回給它們相應的方法:getFootValue()和getInchValue () - 但我不太確定。
我應該如何通過自定義異常來實現這一點?我不能簡單地利用InputMismatchException,我需要創建自己的標題NonDigitNumberException()。
這裏是我迄今爲止...
import java.util.Scanner;
public class Converter
{
private double feet;
private double inches;
public Converter(double feet, double inches)
{
this.feet = feet;
this.inches = inches;
}
public double getFootValue()
{
return feet;
}
public double getInchValue()
{
return inches;
}
public double convertToCentimeters()
{
double inchTotal;
inchTotal = (getFootValue() * 12) + getInchValue();
return inchTotal * 2.54;
}
public String toString()
{
return ("Your result is: " + convertToCentimeters());
}
}
import java.util.Scanner;
import java.util.InputMismatchException;
public class TestConverter
{
public static void main(String[] args)
{
/* Create new scanner for user input */
Scanner keyboard = new Scanner(System.in);
do
{
try
{
/* Get the feet value */
System.out.print("Enter the foot value: ");
double feet = keyboard.nextDouble();
if (feet < 0) throw new NegativeNumberException();
/* Get the inches value */
System.out.print("Enter the inch value: ");
double inches = keyboard.nextDouble();
if (inches < 0) throw new NegativeNumberException();
else
{
Converter conversion = new Converter(feet, inches);
/* Print the converted result */
System.out.println(conversion);
break;
}
} catch(InputMismatchException ignore){}
catch(NegativeNumberException error)
{
System.out.println("A negative-numeric value was entered, please enter only positive-numeric values...");
}
}while(true);
/* Close the keyboard */
keyboard.close();
}
}
class NegativeNumberException extends Exception
{
public NegativeNumberException()
{
super();
}
public NegativeNumberException(String errorMessage)
{
super(errorMessage);
}
}
感謝您的幫助!
你爲什麼要拋出異常呢?您可以打印錯誤消息,而用「繼續」來代替。 – azurefrog
您是否考慮過使用'Scanner.hasNextDouble()'來測試下一個標記是否可以作爲雙精度掃描? –
或者簡單*處理* InputMismatchException發生在輸入不能以雙倍掃描的方式掃描時發生,而不僅僅是忽略它。捕捉異常並忽略它幾乎是不對的。 –