2

Requirement:

Accept 10 numbers, input them into an array and then invoke a method to calculate and return the smallest. This program is suppose to be error proof so when a user enters an invalid entry, it notifies the user and reprompts. I am trying to use try catch but when an invalid entry is entered, ie a character, the scanner won't reprompt.

Any ideas?

Tried:

//Variables
double [] doubleArray = new double[10];
Scanner input = new Scanner(System.in);

//Prompt
System.out.println("This program will prompt for 10 numbers and display the smallest of the group");

//Get values
for (int i = 0; i < doubleArray.length; i++) {
    try {
        System.out.println("Please enter entry "+ (i+1));
        doubleArray[i] = input.nextDouble();        

    } catch (InputMismatchException e) {
        // TODO: handle exception
        System.out.println("Please enter a rational number");
        i--;
    }
}

//Invoke method and display result
System.out.println("The smallest value is: "+index(doubleArray));
Tom Fenech
  • 65,210
  • 10
  • 85
  • 122

4 Answers4

2

I don't see any call to input.nextLine(), which means nothing is ever consuming the \n entered by the user. There's a good example on scanner.nextLine usage here. If you add a call to it in your catch block, you should be all set.

Community
  • 1
  • 1
Nathan
  • 2,003
  • 3
  • 19
  • 33
1

Try calling input.nextLine(); in your catch. Then the \n will be taken from the input which let's you enter the next new number.

for(int i = 0; i < doubleArray.length; ++i) {
    try {
        doubleArray[i] = input.nextDouble();
    } catch(Exception e) {
        input.nextLine();
        --i;
    }
}
Sebastian Höffner
  • 1,655
  • 1
  • 22
  • 32
0

Try something like (and make sure you consume the whole line unless you want to allow multiple numbers to be input on the same line

   boolean validEntry = false;
   System.out.println("Enter a rational number: ");
   while (!validEnry) {
     try {
          double value = input.nextDouble();
          validEntry = true;
          doubleArray[i] = value;
     } catch (Exception e) {
         System.out.println("Entry invalid, please enter a rational number");
     }
   }

   ...
ErstwhileIII
  • 4,691
  • 2
  • 21
  • 36
0

You have to discard the false inputted data, add input.nextLine() in the catch block.

Logos
  • 302
  • 1
  • 6
  • 14