首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java InputMismatchException错误

Java InputMismatchException错误
EN

Stack Overflow用户
提问于 2017-02-28 10:48:17
回答 1查看 78关注 0票数 0

我接到了一个任务,要做一些从ft和in到cm的转换。我已经记录了大部分内容,并且转换确实有效。我还希望在输入字符串或负数时包含A negative number...A non-digit...语句,以显示所述消息。

我遇到的问题是,当我键入一个字符串或负数时,例如,当我输入-9时,我会得到testProgram.NegativeNumberException的输出。和testProgram.NonDigitNumberException,例如,当我输入joe时。

我认为catch中有问题,但不确定它不会点击的确切位置。

代码语言:javascript
复制
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.");
       }
   }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-28 10:56:30

作为@Scary建议的替代方案,您可以将构造函数添加到自定义异常中,如下所示-

代码语言:javascript
复制
NegativeNumberException(String str) {
    System.out.println(str);
}

这将帮助您在以下情况下打印消息

代码语言:javascript
复制
throw new NegativeNumberException ("A n....");
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42499277

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档