2017-02-28 86 views
0

我正在编写一个简单的程序,允许用户输入两个单独的双精度进行英尺和英尺测量。该程序旨在获取这些值并将其转换为厘米并输出。另外我要包括两个例外:一个确保数值是正值而不是负值(我已经完成了这个)和另一个确保输入的值是一个double值而不是一个字符串值(我正在使用这个值很难与)。因此,如果用户输入一个输入...例如'Bill'而不是一个数字,它将显示一条错误消息并要求用户重新输入输入值。Java:使用Try/Catch Exception检查用户输入是否为双精度

看来也许我最好将用户输入作为一个字符串来收集(而不是像我目前所做的那样加倍),我将其转换为双精度并将它们作为双精度返回给它们相应的方法: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); 
    } 
} 

感谢您的帮助!

+0

你为什么要抛出异常呢?您可以打印错误消息,而用“继续”来代替。 – azurefrog

+0

您是否考虑过使用'Scanner.hasNextDouble()'来测试下一个标记是否可以作为双精度扫描? –

+1

或者简单*处理* InputMismatchException发生在输入不能以双倍扫描的方式扫描时发生,而不仅仅是忽略它。捕捉异常并忽略它几乎是不对的。 –

回答

1

你已经过了复杂的事情。您可以简单地使用Scanner.hasNextDouble()方法。

实施例:

假设这个代码是您的主要方法的内部。

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

然后你可以去和使用myValueConverter类。

UPDATE

看来,你必须创建自己的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(); 
    } 
} 
+0

我知道我能做到这一点,但是,我的教授,我不得不利用一个自定义的异常,标题是NonDigitNumberException,它检测/捕获用户是否输入一个双精度值,如果它是一个字符串/字母值,它将返回一个错误消息 –

+0

@KevinGombos好吧,我会实现这一点,并让你更新。 –

+0

@KevinGombos我已经更新了我的回答,以适应你的最新评论,希望这有助于你继续完成你的任务,唯一剩下的就是保持提示用户输入,直到正确的类型(双)被输入。但是,如果你不能这样做,只是让我更新,我愿意帮忙。 –

0

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

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

+0

不幸的是,我不得不根据我的教授在这个任务上的说明使用自定义异常。他指出以下... “NonDigitNumberException(如果步行或英寸输入 值都是非数字) 除了检查为 NegativeNumberException,还查了 NumberFormatException异常的脚或英寸值 那名输入不正确(例如:我输入一个英寸或英尺值的 字母)。当捕捉 NumberFormatException的,然后你会扔你 自己NonDigitNumberException将由try/catch块捕获 。” –

+0

在这种情况下,你可以扔NonDigitNumberException如果hasNextDouble()是假的 – 2017-02-28 22:02:16

0

我猜,你是混合的东西了:

你必须首先验证用户的输入,如果是一个双。如果不是,那么你会得到一个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 
相关问题