简体   繁体   中英

Java: Using Try/Catch Exception to check if user input is 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.

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.

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

Thanks for any help!

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

Example:

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

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

UPDATE

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.

Custom Exception Class

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

Negative Number Exception Class

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

Validator Method

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
}

Negative Number Validator

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

Main method

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

Do you really need a custom exception? Because keyboard.nextDouble() already throws InputMismatchException if the input is not a double.

Instead of ignoring the exception, you should show an error message (saying the user didn't type a number).

I guess, you are mixing things up:

You have to validate the input of the user first, if it is a double. If it is not, then you are getting an InputMismatchException.

Then you have to validate the input, if it is valid for your converter (is it positive?). Here you can throw your custom exception.

And then you call your Converter, which might also throw your custom exception.

So my solution would be:

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

    }
}

Output

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM