1

My Questions:

I'm trying to handle ArrayIndexOutOfBoundsException in my method. Currently it takes in a string of the user's input and if it matches "^[a-zA-Z]*$" (letters/special characters), then it should keep looping. The array size is [26]. When I input 27, it should catch and handle this exception however it just throws the error.

How could I fix this?

public String checkInput(String userInput) {

try {
        while (input.matches("^[a-zA-Z]*$")) {
            System.out.println("Please enter a number");
            userInput = sc.next();
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("The input is invalid, please enter the answer again.");
        userInput = sc.next();
    }

    return userInput;
}

Thanks in advance

1
  • Where is the array? Commented Mar 27, 2018 at 8:30

1 Answer 1

1

In Java, a String does not behave like an array. It is an immutable sequence of characters. And variables are just references to objects. So

userInput = sc.next();

does not modify the original string. The userInput variable just referes a new string and the ref. count of the previous string is decremented. If it reaches 0, it goes out of scope and will be later garbage collected.

Said differently, nothing in your code can raise an ArrayIndexOutOfBoundsException.

If you want to control that the string is not longer than 26, just use its length method:

if (userInput.length() > 26) {
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

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.