So I am working on a Java program that continually ask the user for double values. I am supposed to use a sentinel-controlled loop with sentinel value of -999. I need to use an ArrayList while using try/catch block to handle inputMismatchExceptions, ArrayStoreExeptions, and general Exceptions.
I am currently having trouble trying to finish the program after entering -999, applying message of a duplicate message from ArrayStoreExceptions and to continue input after inputMismatchExceptions.
public static void main(String[] args) {
double d;
double average;
double max;
double min;
ArrayList<Double> value = new ArrayList<Double>();
Scanner input = new Scanner(System.in);
System.out.println("Enter a double value (-999 to exit):");
d = input.nextDouble();
while (!value.equals(-999)) {
try {
System.out.println("Enter a double value (-999 to exit):");
value.add(input.nextDouble());
} catch (InputMismatchException e) {
System.out.println("That is not a valid double value.");
} catch (ArrayStoreException e) {
System.out.println("Duplicate value");
} catch (Exception e) {
System.out.println("Error");
}
}
}
but value is an
ArrayList<Double>
while -999 is just adouble
(an int, actually). You don't want to check if the whole list equals -999, you just want to check if the last inputted value was -999.If you don't want to allow duplicates, you should be using a
Set
, not anArrayList
.When you get an InputMismatchException, you need to call in.nextLine() before asking the user for another double. This is because, if you don't call in.nextLine(), your scanner will still be trying to read the same text that caused the exception the previous time.
Here is a (heavily modified) alteration of your code that should work as you intend it to: (You may want to use a different implementation of
Set
, depending on your needs).I would also recommend you rename "value" to "values" to make it clear that it represents multiple values.
Hope this helps!