2017-02-28 1 views
0

저는 사용자가 발과 인치 측정을 위해 두 개의 별도 double을 입력 할 수있는 간단한 프로그램을 작성하고 있습니다. 이 프로그램은이 값을 취하여 센티미터로 변환하여 출력합니다. 또한 두 가지 예외를 포함해야합니다. 하나는 숫자 값이 음수가 아닌지 확인하고 (이 중 하나는 완료했습니다) 다른 하나는 입력 된 값이 이중 값이고 문자열 값이 아닌지 확인하는 것입니다. 힘든 시간). 따라서 사용자가 숫자 대신에 'Bill'과 같은 입력을 입력하면 오류 메시지를 표시하고 입력 값을 다시 입력하도록 사용자에게 요청하는 것입니다.Java : 사용자 입력이 Double인지 확인하기 위해 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

아니면 단순히 입력을 double로 스캔 할 수없는 경우에 발생하는'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"); 
    } 
    } 
} 

당신은 그때 가서 Converter 클래스 myValue를 사용할 수 있습니다.

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

false 인 경우 NonDigitNumberException을 던질 수있다, 그러나 , 내 교수 당 나는 NonDigitNumberException 사용자가 double 값을 입력했는지 여부를 trys/catch catch하는 사용자 지정 예외를 활용해야하며 문자열/문자 값이면 오류 메시지를 반환합니다. –

+0

@KevinGombos 좋아요, 그걸 구현하고 업데이트 할게요 –

+0

@KevinGombos 최근 의견에 맞는 답변을 업데이트했습니다. 작업을 수행하고 완료하는 데 도움이되기를 바랍니다. 올바른 유형 (두 배)이 될 때까지 입력하라는 메시지를 계속 표시합니다. 입력됩니다. 그러나, 당신이 그것을 할 수 없다면 나는 업데이 트를 계속하고 나는 기꺼이 도와 줄 것입니다. –

0

맞춤 예외가 정말로 필요합니까? 입력이 double이 아니면 keyboard.nextDouble()이 이미 InputMismatchException을 던집니다.

예외를 무시하는 대신 사용자가 숫자를 입력하지 않았다는 오류 메시지가 표시되어야합니다.

+0

불행히도이 작업에 대한 교수 지침에 따라 맞춤 예외를 사용해야합니다. 그는 발 또는 인치의 NumberFormatException이 확인 또한 NegativeNumberException에 대한했다 값들 확인하는 것 외에도 (발 또는 인치 입력 값이 숫자가 아닌 경우) 다음 ... "NonDigitNumberException을 말한다 (예 : 인치 또는 발 값에 문자를 입력 함). 는 NumberFormatException 잡기하면 다음 try/catch 블록에 의해 을 잡힐 것이다 자신의 NonDigitNumberException 발생합니다. " –

+0

을이 경우 hasNextDouble이() 나는이 작업을 수행 할 수 있습니다 알고 –

0

같아요 음수 검사기

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

홈페이지 방법, 당신은 혼합 것들 최대 :

귀하는 경우, 먼저 사용자의 입력을 검증해야 더블입니다. 그렇지 않은 경우 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 
관련 문제