1

I'm sure this is something simple that I just can't spot, I have a do while loop prompting the user for an array size, which will be used for the rest of the program. If the user enters the right input, the program continues and works fine, but if the user enters the wrong input...

public static void main(String[] args)
{
  // user enters up to 20 double values, stored in an array, user should enter 99999 to quit entering numbers. If user has not entered any numbers yet
  // display an error message, otherwise, display each entered value and it's distance from the average

  Scanner keyboard = new Scanner(System.in);
  int arraySize = 0;
  boolean isValid = false;

  do
  {
     isValid = true;
     arraySize = 0; // reset these values at start of each loop.

     System.out.println("Enter an array size.");
     try {
        arraySize = keyboard.nextInt();
     }
     catch(NegativeArraySizeException mistake) {
        System.out.println("Do not enter a negative number for the arrays size.");
        System.out.println();
        isValid = false;
     }
     catch(InputMismatchException mistake) {
        System.out.println("Make sure to enter a valid number.");
        System.out.println();
        isValid = false;
     }
  } while (isValid == false);

If the user enters an invalid input, such as "red", the catch block kicks in and prints "Make sure to enter a valid number." and "Enter an array size." over and over without giving the user a chance to actually enter any input. I figured resetting the arraySize variable would fix it, but it doesn't. I guess the keyboard buffer has stuff in it, but no combination of empty printlns has worked so far.

I've heard that Exceptions shouldn't be used to validate user input. Why is that?

Regardless, it's not relevant to this question, as it is an exercise in Exception handling.

Space Ostrich
  • 363
  • 2
  • 4
  • 11

5 Answers5

2

Without using isValid boolean variable and make simple code for input.

int arraySize = 0;
do {
    System.out.println("Enter a valid array size.");
    try {
        arraySize = Integer.valueOf(keyboard.nextLine());
        if (arraySize < 0) throw new NegativeArraySizeException();// for negative arry size
        break;// loop break when got a valid input
    } catch (Exception mistake) {
        System.err.println("Invalid input: " + mistake);
    }
} while (true);
mmuzahid
  • 2,124
  • 20
  • 37
  • Does "break;" ever cause any issues? I know certain things such as "goto" and the like can cause problems. If it doesn't, that seems like a really elegant way to set up "infinite" loops, and I'll be adopting that as my go to solution for that kind of problem. – Space Ostrich Apr 04 '16 at 02:03
  • 1
    @SpaceOstrich there is no ``goto`` in Java. I have used ``break`` statement for loop exit when got a valid non-negative integer to set array size. May be I'm wrong but you could reduce your code by this way to take just a valid input. – mmuzahid Apr 04 '16 at 05:22
1

You can add a keyboard.nextLine(); in the event of exception and it should resolve the issue.

 try {
    arraySize = keyboard.nextInt();
 }
 catch(NegativeArraySizeException mistake) {
    System.out.println("Do not enter a negative number for the arrays size.");
    System.out.println();
    isValid = false;
    keyboard.nextLine();
 }
 catch(Exception mistake) {
    System.out.println("Make sure to enter a valid number.");
    System.out.println();
    isValid = false;
    keyboard.nextLine();
   }
Sajeev
  • 788
  • 6
  • 23
  • That fixed it. I've just had the thought that adding additional printlines wasn't the way to clear the keyboard buffer after all, it's adding additional nextLines. Sleep deprivation strikes again. – Space Ostrich Apr 04 '16 at 02:04
0

Please see if this fix works for you. Scanner has a problem when you are trying to get the string from nextInt function. In this I have fetched the string and parsed to Integer and then handled the Number format exception

public static void main(String[] args) {
    // user enters up to 20 double values, stored in an array, user should enter 99999 to quit entering numbers. If user has not entered any numbers yet
    // display an error message, otherwise, display each entered value and it's distance from the average

    Scanner keyboard = new Scanner(System.in);
    int arraySize = 0;
    boolean isValid = false;

    do {
        isValid = true;
        arraySize = 0; // reset these values at start of each loop.

        System.out.println("Enter an array size.");
        try {
            arraySize = Integer.parseInt(keyboard.next());
        } catch (NegativeArraySizeException mistake) {
            System.out.println("Do not enter a negative number for the arrays size.");
            System.out.println();
            isValid = false;
        } catch (InputMismatchException mistake) {
            System.out.println("Make sure to enter a valid number.");
            System.out.println();
            isValid = false;
        } catch (NumberFormatException nfe) {
            System.out.println("Make sure to enter a valid number.");
            System.out.println();
            isValid = false;
        }

    } while (isValid == false);
}
Parth Joshi
  • 394
  • 2
  • 6
0

mmuzahid is almost there. But I added a way of checking negative number as well. Try this

    Scanner keyboard = new Scanner(System.in);
    int arraySize = 0;
    boolean isValid = false;
    do {
        System.out.println("Enter a valid array size.");
        try {
            arraySize = Integer.valueOf(keyboard.nextLine());

            if (arraySize < 0) {
                System.out.println("Make sure to enter a valid positive number.");
            } else {
                break;
            }
        } catch (Exception mistake) {
            System.out.println("Make sure to enter a valid number. Error:" + mistake);
        }
    } while (true);
Thush-Fdo
  • 492
  • 8
  • 24
0

Use keyboard.nextLine() and NumberFormatException

do {
            // more code
            try {
                arraySize = Integer.valueOf((keyboard.nextLine()));
            } catch (NegativeArraySizeException mistake) {
                // more code
                isValid = false;
            } catch (InputMismatchException mistake) {
                // more code
                isValid = false;
            } catch (NumberFormatException mistake) {
                // more code
                isValid = false;
            }
} while (isValid == false);
Byaku
  • 1,553
  • 1
  • 14
  • 24
  • [What's the difference between next() and nextLine() methods from Scanner class?] (http://stackoverflow.com/questions/22458575/whats-the-difference-between-next-and-nextline-methods-from-scanner-class) – Byaku Mar 31 '16 at 04:16