[英]Java InputMismatchException Error
I've been given a task to make some conversions from ft and in to cm. 我已经完成了从ft到in到cm的转换任务。 I've gotten most of this down and the conversions do work.
我已经把大部分事情都做了下来,并且转换确实起作用了。 I also want to include the statement of
A negative number...
or A non-digit...
when I type a string, for example, or a negative number, to display said message. 例如,当我键入字符串或负数来显示上述消息时,我还希望包含
A negative number...
或A non-digit...
的语句。
The problem I am getting is that when I do type up a string or negative number, I get the output of testProgram.NegativeNumberException
when I enter -9
, for example. 我得到的问题是,当我输入字符串或负数时,例如,输入
-9
时,将得到testProgram.NegativeNumberException
的输出。 And testProgram.NonDigitNumberException
, when I enter joe
, for example. 还有
testProgram.NonDigitNumberException
,例如,当我输入joe
时。
I am thinking there is something wrong in the catch
but not sure exactly where it won't click. 我在想
catch
有问题,但不能确切确定它不会卡在哪里。
package testProgram;
import java.util.InputMismatchException;
import java.util.Scanner;
public class conversion{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double cm = -1;
while(cm == -1){
cm = convertToCentimeters(scan);
if(cm!=-1){
System.out.println("Your result = " +cm);
}
else{
System.out.println("Please enter the values again.");
}
scan.nextLine();
}
}
public static double convertToCentimeters(Scanner scan){
double centimeters = -1;
try{
double foot = getFootValue(scan);
double inch = getInchValue(scan);
double totalInches = foot * 12 + inch;
centimeters = totalInches * 2.54;
}catch(NegativeNumberException e1){
System.out.println(e1);
}
catch(NonDigitNumberException e2){
System.out.println(e2);
}
return centimeters;
}
public static double getFootValue(Scanner scan) throws NegativeNumberException, NonDigitNumberException{
try{
System.out.println("Enter the foot value: ");
double foot = scan.nextDouble();
if(foot <= 0){
throw new NegativeNumberException ("A negative foot value has been entered.");
}
return foot;
}
catch(InputMismatchException e){
throw new NonDigitNumberException ("A non-digit foot value has been entered.");
}
}
public static double getInchValue(Scanner scan)throws NegativeNumberException, NonDigitNumberException{
try{
System.out.println("Enter the inch value: ");
double inch = scan.nextDouble();
if(inch <= 0){
throw new NegativeNumberException ("A negative inch value has been entered.");
}
return inch;
}
catch(InputMismatchException e){
throw new NonDigitNumberException ("A non-digit inch value has been entered.");
}
}
}
Alternatively to @Scary's suggestion, you can add a constructor to your custom exceptions as - 除了@Scary的建议之外,您还可以将构造函数添加到自定义异常中,如下所示:
NegativeNumberException(String str) {
System.out.println(str);
}
This shall help you print the message when you 这将帮助您在您打印消息时
throw new NegativeNumberException ("A n....");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.