Need help with a method exception!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sekm
    New Member
    • Mar 2008
    • 1

    Need help with a method exception!

    Hi there i want a basic menu which the user inputs a number to chose from the menu. Thing is that i need to make sure that the input IS an integer. So i have an InputMismatchEx ception catch but when it occurs, the program just keeps outputting the menu over and over??

    [code=java]
    static Scanner sc = new Scanner(System. in);

    public static void menu (){
    System.out.prin tln("Please enter a number to select from the following:\n\t1 . Create new Array\n\t2. Load array from MyObject.dat");
    int choice = 0;
    try{
    choice = sc.nextInt();
    switch(choice){
    case 1:
    start();
    break;
    case 2:
    loadArray();
    break;
    default :
    System.out.prin tln("invalid");
    }
    }catch (InputMismatchE xception e){
    System.out.prin tln("Please enter a valid NUMBER from the menu... Resetting menu.");
    }
    menu();
    }[/code]
    Last edited by JosAH; Mar 30 '08, 06:47 AM. Reason: added [code] ... [/code] tags
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Suppose you make your scanner read a nextInt(). If there isn't an int in the input
    the scanner doesn't read anything and throws an exception as you have noticed.
    If you immediately make it read another nextInt() the scanner sees the same
    input and the story repeats itself (i.e. nothing read and an exception thrown) etc.

    Simply skip the line that doesn't contain an integer and caused an exception
    to be thrown.

    kind regards,

    Jos

    Comment

    • hsn
      New Member
      • Sep 2007
      • 237

      #3
      so read it as a string, make sure it is not a char then convert it to integer by using the parse function......

      good luck

      hsn

      Comment

      Working...