-1

I've comment on the line. Why will that line not take another input? And then keep repeating until an integer is input.

import java.util.*;

class ScanNumbers{

   public static void main(String[] args){

      Scanner scan = new Scanner(System.in);

      int[] NumberEntry = new int[6];

         for (int i = 1; i < NumberEntry.length; i++){

            boolean isInteger = false;

            while (!isInteger){

            try {
                System.out.print("Entry " +i + "/5, enter an integer value: ");
                NumberEntry[i] = scan.nextInt();
               isInteger = true;
             }

            catch (Exception e){
               System.out.print("Entry " +i + "/5, Please enter only an integer value: ");
               NumberEntry[i] = scan.nextInt(); //Right here, I would like to ask again, why is this line not doing the job?
            }
         }
      }
         Arrays.sort(NumberEntry);
         System.out.print("The max integer is: " +  + NumberEntry[NumberEntry.length-1]);
   }
}

Can't I just tell it to try the catch again?

Edit 1: Haha, Oh my, Thanks, I have removed the line, but now the out put keeps repeating "Entry 1/5, enter an integer value:"

Edit 2: Thanks! Works fine now!

user2155190
  • 1
  • 1
  • 5
  • This is similar to a post I found in this forum [here](http://stackoverflow.com/questions/6612806/infinite-while-loop-when-inputmidmatchexception-is-caught-in-try-catch-block) – V.G Mar 11 '13 at 02:23
  • Your array is of size 6 ,but with your current for loop it takes only 5 values. Array index starts from 0. – Abi Mar 11 '13 at 02:24
  • possible duplicate of [Exception thrown inside catch block - will it be caught again?](http://stackoverflow.com/questions/143622/exception-thrown-inside-catch-block-will-it-be-caught-again) – CloudyMarble Mar 11 '13 at 06:43

1 Answers1

4

What's happening is that the invalid input is being kept in the Scanner. You have to skip the input so you can go back to accepting valid data. Without doing that, the exception will be caught over and over. There is also an easier way to do what you're trying to do. Try this:

try {
    System.out.print("Entry " +i + "/5, enter an integer value: ");
    NumberEntry[i] = scan.nextInt();
}
catch (Exception e){
    scan.next();
    i--;
    continue;
}

This skips the undesired input. It also restarts your loop on the same iteration.

Memento Mori
  • 3,327
  • 2
  • 22
  • 29