Michael
Michael

Reputation: 3229

Errors using the try catch block

I am having some problems when I run this code. It executes the first and second System.out.println just fine. The program then calls IOHelper and it allows me to input a number. Once I enter the value, it prints "Obtained: xxxx" and then prints "Please enter the wind velocity:" followed by this list of errors.

Exception in thread "main" java.util.NoSuchElementException    
at java.util.Scanner.throwFor(Unknown Source)    
at java.util.Scanner.next(Unknown Source)   
at java.util.Scanner.nextDouble(Unknown Source)   
at Assignment1_14.IOHelper(Assignment1_14.java:49)   
at Assignment1_14.main(Assignment1_14.java:27)

I am using eclipse.

public class Assignment1_14 {

// declaring constants
final static double GRAVITY = 9.807;
final static double MASS_INITIAL = 0.008;
final static int LAUNCH_VEL = 22;
final static int DENSITY = 1900;
final static double BURN_RATE = 0.003;
final static int MIN_ANGLE = -15;
final static int MAX_ANGLE = 15;
final static int MIN_WIND = -22;
final static int MAX_WIND = 22;

public static void main(String[] args){
    System.out.println("Hello, in order to launch the Roman Candle, please set \n"
            + "the launch angle and wind velocity. Note, the launch angle must be \n"
            + "between 15 degrees and -15 degrees.\n\n");

    System.out.println("Please enter the launch angle: ");
    double angle = IOHelper(MIN_ANGLE, MAX_ANGLE);
    System.out.println("Obtained: " + angle);

    System.out.println("Please enter the wind velocity: ");
27  double windVel = IOHelper(MIN_WIND, MAX_WIND);
    System.out.println("Obtained: " + windVel);
} // end main method

public static double IOHelper (double low, double high) {
    Scanner screen = new Scanner(System.in);
    double num = 0;
    boolean inputOK = false;
    String dump = null;

    while (!inputOK) {
        try {
    49      num = screen.nextDouble();
            dump = screen.nextLine();

            if (num < low || num > high) {
                inputOK = false;
                continue;
            } // end if statement
            inputOK = true;
        } catch (InputMismatchException e) {
            dump = screen.nextLine();
            System.out.println("\"" + dump + "\" is not a legal double, "
            + "please try again!");
        } // end try-catch block
    } // end input loop
    screen.close();
    return num;
} // end IOHelper method

Upvotes: 1

Views: 67

Answers (1)

OYRM
OYRM

Reputation: 1415

The NoSuchElement exception gets thrown because there is no element to read. https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next%28%29

Either catch it, or add a check for input before you read a token

while (!inputOK) {
    try {
        if(!screen.hasNext()) continue;
        num = screen.nextDouble();
....

Upvotes: 2

Related Questions