Kevin Gombos Kevin Gombos -4 years ago 246
Java Question

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!

Answer Source

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();
   }
 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download