0

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");
}

}

1 Answer 1

1

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.");

    }
Sign up to request clarification or add additional context in comments.

2 Comments

Add some explanation, to understand better.
Great! So this works how I want it to work to accept only words and throw an exception when the user enters only numbers. Note: with Patter pattern = Pattern.compile("-?[0-9]+.?[0-9]+") it doesn't throw an exception with single digits. So I modified the line with: Pattern pattern = Pattern.compile("-?[0-9]+"); and now it works perfectly! Thank you @MakerStack!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.