【问题标题】:Java: Using Try/Catch Exception to check if user input is DoubleJava:使用 Try/Catch Exception 检查用户输入是否为 Double
【发布时间】: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


【解决方案1】:

你把事情复杂化了。您可以简单地使用Scanner.hasNextDouble() 方法。

示例:

假设这段代码在你的 main 方法中。

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 类。

更新

看来你必须根据你在cmets中告诉我的内容创建你自己的exceptionclass。所以,我决定为你实现它,希望你能从这里继续。

自定义异常类

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

【讨论】:

  • 我知道我可以做到这一点,但是,根据我的教授,我必须使用一个自定义异常,它的标题是 NonDigitNumberException,它尝试/捕获用户是否输入了双精度值,如果是字符串/字母值,则返回错误消息。
  • @KevinGombos 好的,我会实施并让您随时更新。
  • @KevinGombos 我已更新我的答案以适合您的最新评论。希望这确实可以帮助您继续并完成您的任务。唯一剩下的就是不断提示用户输入,直到输入正确的类型(双精度)。但是,如果您不能这样做,请让我更新,我愿意提供帮助。
  • 这非常成功。我继续为每个变量制作了两个验证器,它们可以工作。然而。现在我注意到我的 NegativeNumberException() 不起作用。 NonDigitNumberException() 似乎过度统治它。因此,当输入负数而不是显示 NegativeNumberException 的 catch 输出时,它会显示 NonDigitNumberException() 输出。我想知道是否有办法纠正这个问题?否则效果很好!
  • @KevinGombos 肯定有。如果解决方案解决了您的问题,如果您将答案标记为已接受,我将不胜感激。另外,与此同时,我会告诉你如何克服你最近遇到的问题。
【解决方案2】:

您真的需要自定义异常吗?因为如果输入不是双精度,keyboard.nextDouble() 已经抛出 InputMismatchException。

您应该显示一条错误消息(说明用户没有输入数字),而不是忽略异常。

【讨论】:

  • 不幸的是,我必须根据教授关于此任务的说明使用自定义异常。他陈述如下......“NonDigitNumberException(如果英尺或英寸输入值不是数字)除了检查 NegativeNumberException 之外,还要检查输入不正确的英尺或英寸值的 NumberFormatException(例如:我输入英寸或英尺值的字母)。当捕获 NumberFormatException 时,您将抛出自己的 NonDigitNumberException,该异常将被 try/catch 块捕获。"
  • 在这种情况下,如果 hasNextDouble() 为 false,您可能会抛出 NonDigitNumberException
【解决方案3】:

我猜,你把事情搞混了:

您必须首先验证用户的输入,如果它是双精度。如果不是,那么您将收到 InputMismatchException。

然后你必须验证输入,如果它对你的转换器有效(它是积极的吗?)。在这里你可以抛出你的自定义异常。

然后您调用您的转换器,这也可能引发您的自定义异常。

所以我的解决方案是:

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 {
            double feet = -1, inches = -1;
            Exception exception;
            do {
                exception = null;
                /* Get the feet value */
                System.out.print("Enter the foot value (positive-numeric): ");
                try {
                    feet = keyboard.nextDouble();
                } catch (InputMismatchException e) {
                    keyboard.next();
                    exception = e;
                }
            } while (exception != null);
            do {
                exception = null;
                /* Get the inches value */
                System.out.print("Enter the inch value (positive-numeric): ");
                try {
                    inches = keyboard.nextDouble();
                } catch (InputMismatchException e) {
                    keyboard.next();
                    exception = e;
                }
            } while (exception != null);


            try {
                if (feet < 0) throw new NegativeNumberException();
                if (inches < 0) throw new NegativeNumberException();

                Converter conversion = new Converter(feet, inches);

                /* Print the converted result */
                System.out.println(conversion);
                break;
            }
            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();

    }
}

输出

Enter the foot value (positive-numeric): test
Enter the foot value (positive-numeric): 1234
Enter the inch value (positive-numeric): test
Enter the inch value (positive-numeric): 1234
Your result is: 40746.68

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多