2017-02-28 137 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