javainputmismatchexception

How do I message an end user that they are entering the wrong input and/or format without getting an Exception/Crash?


"Eclipse IDE for Java Developers (includes Incubating components) Version: 2023-03 (4.27.0)" Intro to Programming using Java Section 3.5.3

Sorry for the very long post. This is my first post anywhere about programming. Thanks for any help! I would appreciate any other recommendations if this book is not a good one to learn java from.

The below is from the above online textbook that I am using to try an learn Java. I have issues with Exceptions in the program. For Example: Once running the program, everything seems to be working fine until I enter a format that the program does not expect. I want it to skip to "else" and print the message if an incorrect format is entered, but for some reason it just Excepts out. The end user is suppose to enter something like "56 inches" or "156 feet" so that it can be converted and display in multiple different units, but if I just enter "inches" it gives me the blow exception because I skipped the measurement variable.

How do I make this program output a reasonable message to the end user, if they are entering the incorrect format that afterwards places them back at the input directions?

----*Error*---
**"Enter your measurement, or 0 to end: inches
Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
    at UnitConversionTextBook.main(UnitConversionTextBook.java:22)"**

---Program---

import java.util.Scanner;

public class UnitConversionTextBook {
public static void main(String[] args) {
    
    String units; 
    double measurement; 
    double inches, feet, yards, miles; 
    
        System.out.println("""
                Enter measurements in inches, feet, yards, or miles.
                Some examples: 1 inch or 17 feet or 2.73 miles
                You can use the abbreviations: in ft yd mi
                Please press enter after typing your measurement.
                I will also convert your input into the other units
                of measurements.
                """);
                                                                                                                                                                            
        while (true) {
    
        System.out.print("Enter your measurement, or 0 to end: ");
        Scanner stdio = new Scanner(System.in);
        measurement = stdio.nextDouble();
        units = stdio.next();
        units = units.toLowerCase();
        
        if (measurement == 0) {
        break; 
        }
        if (units.equals("inch") || units.equals("inches")|| units.equals("in")) {
        inches = measurement;
        }
        else if (units.equals("foot") || units.equals("feet")|| units.equals("ft")) {
        inches = measurement * 12;
        }
        else if (units.equals("yard") || units.equals("yards")|| units.equals("yd")) {
        inches = measurement * 36;
        }
        else if (units.equals("mile") || units.equals("miles")|| units.equals("mi")) {
        inches = measurement * 12 * 5280;
        }
        else {
                System.out.println("Sorry, but I don’t understand \""
        + units + "\".");
        continue; 
        }
        
        feet = inches / 12;
        yards = inches / 36;
        miles = inches / (12*5280);
        
        System.out.println();
        System.out.printf("""
            That’s equivalent to:
            %14.5g inches
            %14.5g feet
            %14.5g yards
            %14.5g miles
            """, inches, feet, yards, miles);
        System.out.println();
                
        }
    
    }
        
}

I have tried entering parameters into the while statement, other silly attempts, but I am just starting out so it is pretty pointless to share. I would like for something to work like

if end user does not enter numerical measurement first followed by unit measurement type then message user they are not following directions and to please enter the input with the correct format that has been reasonably dictated.

first input should be a double(measurement) second input should be string(unit) the way this book codes it is they are both to be inputted on the same line followed by pressing the enter key.


Solution

  • There are two ways at high level to fix this

    Way 1: You need to wrap your logic inside a try-catch. Here it needs the InputMismatchException handling as you are expecting double but it is coming as something else you may have other scenarios as well where you can make it multi-catch.

    import java.util.InputMismatchException; import java.util.Scanner;

    public class UnitConversionTextBook { public static void main(String[] args) {

        String units;
        double measurement;
        double inches, feet, yards, miles;
    
        System.out.println(
                "Enter measurements in inches, feet, yards, or miles.Some examples: 1 inch or 17 feet or 2.73 miles You can use the abbreviations: in ft yd mi Please press enter after typing your measurement.  I will also convert your input into the other units of measurements.");
    
        while (true) {
    
            try {
                System.out.print("Enter your measurement, or 0 to end: ");
                Scanner stdio = new Scanner(System.in);
                measurement = stdio.nextDouble();
                units = stdio.next();
                units = units.toLowerCase();
    
                if (measurement == 0) {
                    break;
                }
                if (units.equals("inch") || units.equals("inches") || units.equals("in")) {
                    inches = measurement;
                } else if (units.equals("foot") || units.equals("feet") || units.equals("ft")) {
                    inches = measurement * 12;
                } else if (units.equals("yard") || units.equals("yards") || units.equals("yd")) {
                    inches = measurement * 36;
                } else if (units.equals("mile") || units.equals("miles") || units.equals("mi")) {
                    inches = measurement * 12 * 5280;
                } else {
                    System.out.println("Sorry, but I don’t understand \"" + units + "\".");
                    continue;
                }
    
                feet = inches / 12;
                yards = inches / 36;
                miles = inches / (12 * 5280);
    
                System.out.println();
                System.out.printf("That’s equivalent to: %14.5g inches %14.5g feet %14.5g yards %14.5g miles", inches,
                        feet, yards, miles);
    
                System.out.println();
            } catch (InputMismatchException e) {
                // TODO Auto-generated catch block
                System.out.println("Please read instructions again and retry");
                continue;
            }
    
        }
    
    }
        
    

    }

    Way 2: Wrap only double reading code in try - catch But remember to initilize a value to local variable

    public class UnitConversionTextBook {
    public static void main(String[] args) {
    
        String units;
        double measurement=0;
        double inches, feet, yards, miles;
    
        System.out.println(
                "Enter measurements in inches, feet, yards, or miles.Some examples: 1 inch or 17 feet or 2.73 miles You can use the abbreviations: in ft yd mi Please press enter after typing your measurement.  I will also convert your input into the other units of measurements.");
    
        while (true) {
    
             
                System.out.print("Enter your measurement, or 0 to end: ");
                Scanner stdio = new Scanner(System.in);
                try {
            
                    measurement = stdio.nextDouble();
                } catch (InputMismatchException e) {
                    // TODO Auto-generated catch block
                    System.out.println("Please read instructions again and retry");
                    continue;
                }
                units = stdio.next();
                units = units.toLowerCase();
    
                if (measurement == 0) {
                    break;
                }
                if (units.equals("inch") || units.equals("inches") || units.equals("in")) {
                    inches = measurement;
                } else if (units.equals("foot") || units.equals("feet") || units.equals("ft")) {
                    inches = measurement * 12;
                } else if (units.equals("yard") || units.equals("yards") || units.equals("yd")) {
                    inches = measurement * 36;
                } else if (units.equals("mile") || units.equals("miles") || units.equals("mi")) {
                    inches = measurement * 12 * 5280;
                } else {
                    System.out.println("Sorry, but I don’t understand \"" + units + "\".");
                    continue;
                }
    
                feet = inches / 12;
                yards = inches / 36;
                miles = inches / (12 * 5280);
    
                System.out.println();
                System.out.printf("That’s equivalent to: %14.5g inches %14.5g feet %14.5g yards %14.5g miles", inches,
                        feet, yards, miles);
    
                System.out.println();
            
    
        }
    
    }
        
    

    }