我正在编写一个简单的程序,允许用户输入两个单独的双精度进行英尺和英尺测量。该程序旨在获取这些值并将其转换为厘米并输出。另外我要包括两个例外:一个确保数值是正值而不是负值(我已经完成了这个)和另一个确保输入的值是一个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发生在输入不能以双倍扫描的方式扫描时发生,而不仅仅是忽略它。捕捉异常并忽略它几乎是不对的。 –