Java:使用“尝试/捕获"异常检查用户输入是否为Double [英] Java: Using Try/Catch Exception to check if user input is Double

查看:84
本文介绍了Java:使用“尝试/捕获"异常检查用户输入是否为Double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的程序,该程序允许用户输入两个单独的双精度值来进行英尺和英寸的测量.该程序旨在获取这些值并将其转换为厘米并输出.另外,我要包括两个例外:一个是确保数值为正而不是负(我已经完成了此操作),另一个是确保输入的输入是双精度值而不是字符串值(这是我所拥有的)很难).因此,如果用户输入输入...例如帐单"而不是数字,则将显示一条错误消息,并要求用户再次重新输入输入值.

I am writing a simple program that allows a user to enter two separate doubles for a foot and inch measurement. The program is intended to take these values and convert them to centimeters and output them. Additionally I am to include two exceptions: one to make sure the numeric values are positive and not negative (this one I have completed) and another to make sure the input entered is a double value and not a string value (this one I am having a hard time with). So if a user enters an input... for example 'Bill' instead of a number, it is to display an error message and ask the user to re-enter the input values again.

似乎最好将用户输入作为字符串收集(而不是像我目前那样是双精度),我将其转换为双精度并将其作为双精度返回给其对应的方法:getFootValue()和getInchValue()-但我不太确定.

It seems like perhaps I would be best off gathering the user input as a string (rather than doubles as I currently am), which I convert to doubles and return them as doubles to their corresponding methods: getFootValue() and getInchValue() -- but I am not too sure.

我应该如何通过自定义异常来实现此目标?我不能简单地利用InputMismatchException,我需要创建自己的标题为NonDigitNumberException().

How should I go about implementing this by way of a custom exception? I cannot simply utilize the InputMismatchException, I need to make my own titled NonDigitNumberException().

这是我到目前为止所拥有的...

Here is what I have so far...

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);
    }
}

感谢您的帮助!

推荐答案

您已经使事情变得复杂了.您可以简单地使用 Scanner.hasNextDouble()方法.

You're over complicating things. You can simply use the Scanner.hasNextDouble() method.

示例:

假设此代码位于您的main方法内部.

Assuming this code is inside your main method.

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("enter value");
    double myValue = 0;
    if(scanner.hasNextDouble()){
      myValue = scanner.nextDouble();
    }else{
      System.out.println("Wrong value entered");
    }
  }
}

然后您可以继续将 myValue 与您的 Converter 类一起使用.

you can then go on and use myValue with your Converter class.

更新

似乎您必须根据您在评论中告诉我的内容创建自己的 exception class .因此,我决定为您实施该程序,希望您可以从这里继续进行.

It seems that you must create your own exception class according to what you have told me within the comments. So, I have decided to implement that for you and hopefully, you can be able to carry on from here.

自定义例外类别

public class NonDigitNumberException extends InputMismatchException {
    public NonDigitNumberException(String message){ // you can pass in your own message
        super(message);
    }

    public NonDigitNumberException(){ // or use the default message
        super("input is not a digit");
    }
}

负数例外类别

public class NegativeNumberException extends IllegalArgumentException {
    public NegativeNumberException(String message){ // you can pass in your own message
        super(message);
    }

    public NegativeNumberException(){ // or use the default message
        super("negative number is not valid");
    }
}

验证器方法

public static double inputValidator(){
  Scanner scanner = new Scanner(System.in);
  System.out.println("enter a value"); // prompt user for input
  String getData = scanner.next(); // get input
  if(getData.length() >= 1){
        if(!Character.isDigit(getData.charAt(0)) && getData.charAt(0) != '-') throw new NonDigitNumberException();
  }
  for (int i = 1; i < getData.length(); i++) {
     if(!Character.isDigit(getData.charAt(i))) throw new NonDigitNumberException();
  }
  return Double.parseDouble(getData); // at this point the input data is correct
}

负数验证器

public static boolean isNegative(double value){
   if(value < 0) throw new NegativeNumberException();
   return false;
}

主要方法

 public static void main(String[] args) {
   try {
     double myValue = inputValidator();
     System.out.println(isNegative(myValue)); // check if number is negative
   }catch (NegativeNumberException e){
     e.printStackTrace();
   }
   catch (NonDigitNumberException e){
     e.printStackTrace();
   }
   catch(Exception e){
     e.printStackTrace();
   }
 }

这篇关于Java:使用“尝试/捕获"异常检查用户输入是否为Double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆