简体   繁体   中英

Java, try-catch with Scanner

I am creating a small algorithm and this is a part of it.

If the user enters non integer values, I want to output a message and let the user enter a number again:

boolean wenttocatch;

do 
{
    try 
    {
        wenttocatch = false;
        number_of_rigons = sc.nextInt(); // sc is an object of scanner class 
    } 
    catch (Exception e) 
    {
        wenttocatch=true;
        System.out.println("xx");
    }
} while (wenttocatch==true);

I am getting a never ending loop and I can't figure out why.

How can I identify if the user enters some non integer number?
If the user enters a non integer number, how can I ask the user to enter again?

Update
When I am printing the exception I get 'InputMismatchException', what should I do?

The Scanner does not advance until the item is being read. This is mentioned in Scanner JavaDoc . Hence, you may just read the value off using .next() method or check if hasInt() before reading int value.

boolean wenttocatch;
int number_of_rigons = 0;
Scanner sc = new Scanner(System.in);

do {
    try {
        wenttocatch = false;
        number_of_rigons = sc.nextInt(); // sc is an object of scanner class
    } catch (InputMismatchException e) {
        sc.next();
        wenttocatch = true;
        System.out.println("xx");
    }
} while (wenttocatch == true);

You dont have to do a try catch. This code will do the trick for you :

public static void main(String[] args) {
    boolean wenttocatch = false;
    Scanner scan = new Scanner(System.in);
    int number_of_rigons = 0;
    do{
        System.out.print("Enter a number : ");
        if(scan.hasNextInt()){
            number_of_rigons = scan.nextInt();
            wenttocatch = true;
        }else{
            scan.nextLine();
            System.out.println("Enter a valid Integer value");
        }
    }while(!wenttocatch);
}

Anytime you get an exception, wenttocatch is set to true and the program will be stuck in an infinite loop. As long as you don't get the exception you'll not get an infinite loop.

The logic if sc.nextInt() causing the error is this

1) wenttocatch is set to false

2) sc.nextInt() throws error

3) wenttocatch is set to true

4) repeat[because wenttocatch is true]

To solve this set wentocatch=false in catch statement

catch (Exception e) {
               wenttocatch=false;
               System.out.println("xx");
            }

if you are doing more than you show here, use a counter[if your counting or a boolean if you are not], but unless you are doing more, do the first thing above

boolean wenttocatch;
int count = 0;

            do{


             try {
                 wenttocatch=false;
                number_of_rigons=sc.nextInt(); // sc is an object of scanner class 
            } catch (Exception e) {
               count++;
               wenttocatch=true;
               System.out.println("xx");

            }

            }while(wenttocatch==true && count < 1);

Answer Comment:

I think you want to get ints until a user doesn't enter anymore. Depending on your input one way of doing that is this

int number_of_rigons;
while((number_of_rigons = sc.nextInt()) != null){
    //do something
}

you simply can use the hasNext(); method in java, instead of try and catch. The hasNext() is a method of Java Scanner class that returns true if this scanner has another token in its input.

 String[] stringArray = new String[lines];
   int i = 0;
   try (Scanner sc = new Scanner(file)) {
       while (sc.hasNextLine()) {
           String data=sc.nextLine();
           stringArray[i] = data;

           i++;
       }
   } catch (FileNotFoundException fileNotFoundException) {
       System.err.println("Error opening file.");
       throw new FileNotFoundException();
   } catch (NoSuchElementException e) {
       System.err.println("Error in file record structure");
       throw new NoSuchElementException();
   } catch (Exception e) {
       e.printStackTrace();
   }
  

/*added the scanner declaration inside try im new on programming its worked for me but I don't know if its good practice */ :

    boolean wenttocatch;
    do 
    {
        try 
        {
           
        Scanner sc=new Scanner(System.in);
         wenttocoatch = false;
        number_of_rigons = sc.nextInt(); 
    } 
    catch (Exception e) 
    {
        wenttocatch=true;
        System.out.println("xx");
    }
} while (wenttocatch==true);
....
try {
  ....
} catch (Exception e) {
  sc.next();
  wenttocatch=true;
  System.out.println("xx");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM