Home > Software engineering >  Catching an exception when a user inputs an integer while using a Scanner object
Catching an exception when a user inputs an integer while using a Scanner object

Time:11-10

I'm trying to catch an exception when the user enters any integer in the Scanner. I understand that using a String item = scan.nextLine() will allow for any input to be made including integers. I created a custom exception to catch the number 1. But what happens if the user inputs 999 or any other integer. How can I catch those other integers as part of the exception?

import java.util.Scanner; import java.lang.Exception;

public class ExampleOne {

public static void main(String[] args) throws TestCustomException {
    
    System.out.println("Please enter any word:");
    
    try {
        
        Scanner scan = new Scanner(System.in);
        String item = scan.nextLine();
        if (item.contains("1")) {
            throw new TestCustomException();
        } 
    }catch (TestCustomException e) {
        System.out.println("A problem occured:  "   e);
    }
    
    System.out.println("Thank you for using my application.");
    
}

}

public class TestCustomException extends Exception {

TestCustomException (){
    super("You can't enter any number value here");
}

}

CodePudding user response:

Regular expression

public static void main(String[] args) {
        System.out.println("Please enter any word:");
        try {
            Scanner scan = new Scanner(System.in);
            String item = scan.nextLine();

            Pattern pattern = Pattern.compile("-?[0-9] .?[0-9] ");
            Matcher isNum = pattern.matcher(item);

            if (isNum.matches()) {
                throw new RuntimeException();
            }
        }catch (RuntimeException e) {
            System.out.println("A problem occured:  "   e);
        }
        System.out.println("Thank you for using my application.");

    }
  • Related