【发布时间】:2017-02-28 21:27:20
【问题描述】:
我正在编写一个简单的程序,它允许用户输入两个单独的双精度数来测量英尺和英寸。该程序旨在获取这些值并将它们转换为厘米并输出它们。另外我要包括两个例外:一个确保数值是正数而不是负数(这个我已经完成),另一个确保输入的输入是双精度值而不是字符串值(这个我有很难相处)。因此,如果用户输入一个输入...例如“Bill”而不是数字,则会显示错误消息并要求用户再次重新输入输入值。
似乎我最好将用户输入收集为一个字符串(而不是像我现在这样的双精度),我将其转换为双精度并将它们作为双精度返回到相应的方法: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);
}
}
感谢您的帮助!
【问题讨论】:
-
你为什么要抛出异常?您可以只打印错误消息和
continue。 -
你有没有考虑过使用
Scanner.hasNextDouble()来测试下一个token是否可以被扫描为double? -
或者简单地处理当输入不能被扫描为双精度时发生的
InputMismatchException,以某种比忽略它更有用的方式。捕捉异常并忽略它几乎从来都不是正确的做法。 -
我必须使用自定义异常来测试输入的是双精度值还是字符串值——不幸的是。这是我的教练要求的。
-
感谢句柄上的提示,我对使用异常比较陌生,所以我不太确定如何忽略当用户输入字符串而不是输入字符串时关闭程序的错误加倍并改用自定义异常。
标签: java exception input double try-catch