Java code - Handling exceptions - HELP!!!

Discussion in 'Programmer's Corner' started by krow, Aug 7, 2011.

  1. krow

    Thread Starter Member

    May 25, 2010
    49
    0
    Hello guys,

    A few days ago I posted a similar question about a Java code, here's one more, I hope you can help me out.

    The problem I have is this, when you enter a character the program is supposed to loop the whole thing AND run the scanner asking for data until the user (assuming the user is quite dumb) finally enters an integer value, I'm getting an endless loop I don't know why and the program won't run the scanner a second time, why's that?


    import java.util.*;

    public class tryCatch {
    public static void main (String args[]){
    Scanner ms = new Scanner(System.in);
    int number;
    int x=1;

    do{
    try{

    System.out.println("Enter your number: ");
    number = ms.nextInt();
    System.out.println("Your number is: " + number);
    x=2;

    }

    catch(InputMismatchException f){
    System.out.println("Error! integer values, only!");

    }

    }while(x==1);
    }
    }
     
  2. SgtWookie

    Expert

    Jul 17, 2007
    22,182
    1,728
    Just adding CODE tags to preserve your formatting.
     
  3. krow

    Thread Starter Member

    May 25, 2010
    49
    0
    Well, my code n NetBeans looks just like the one you just pasted but I still have the same problem.

     
  4. krow

    Thread Starter Member

    May 25, 2010
    49
    0
    I forgot to mention I'm new to Java, been learning for like 3 weeks now so whoever can help me, please do it as if you were teaching a 10-year old boy :)
     
  5. kubeek

    AAC Fanatic!

    Sep 20, 2005
    4,670
    804
    try this:
    Code ( (Unknown Language)):
    1. package javaapplication1;
    2.  
    3. import java.util.*;
    4.  
    5.  
    6. public class JavaApplication1 {
    7.  
    8.     public static void main(String args[]) {
    9.         Scanner ms;
    10.         int number;
    11.  
    12.        while(true) {
    13.             try {
    14.                 ms = new Scanner(System.in);
    15.                 System.out.println("Enter your number: ");
    16.                 number = ms.nextInt();
    17.                 System.out.println("Your number is: " + number);
    18.  
    19.  
    20.             } catch (InputMismatchException f) {
    21.                 System.out.println("Error! integer values, only!");
    22.             }
    23.  
    24.         }
    25.     }
    26. }
    and please next time use the right click -> format, and use it often.
     
  6. krow

    Thread Starter Member

    May 25, 2010
    49
    0
    Thanks Kubeek,

    Well I'm pretty new to programming and I didn't know anything about the format thing when you copy and paste a code.

    I fixed the problem by the way, I just added "ms.next();" in the Catch and it worked the way I wanted, thanks anyway.
     
Loading...