Xavier
Xavier

Reputation: 43

Array Out of Bounds issue

I have a very simple program with one textbox, and a button.

The user is told to put the name of two colors in the box, separated by a space.

For example "red green" The output will print on the screen, "The apple is red with green dots.".

However I need it to function when there is only one word entered on the screen. I am using an array holding the split strings. When I only type in red, I get this error.

"AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException:

Here is the code:

String userInput = textField.getText();
String[] userInputSplit = userInput.split(" ");
String wordOne = userInputSplit[0];
String wordTwo = userInputSplit[1];
if (wordTwo !=null){
                System.out.println("The apple is " + wordOne + " with " + wordTwo + " dots.");
                } else {
                 System.out.println("The apple is " + wordOne + " with no colored dots.");
                }

Upvotes: 1

Views: 961

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347184

You could also do a pre-condition check to see if the input from the user contains any spaces...

String userInput = textField.getText();
userInput = userInput.trim(); // Remove any leading/trailing spaces
if (userInput != null && userInput.length() > 0) {
    StringBuilder msg = new StringBuilder(64);
    if (userInput.contains(" ")) {
        String[] userInputSplit = userInput.split(" ");
        String wordOne = userInputSplit[0];
        String wordTwo = userInputSplit[1];
        msg.append("The apple is ").append(wordOne);
        msg.append(" with ").append(wordTwo).append(" dots");
    } else {
        msg.append("The apple is ").append(userInput).append(" with no colored dots.");
    }
    System.out.println(msg);
} else {
    // No input condition...
}

That's just another way of looking at the problem...

Upvotes: 2

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26058

Could just do something easy like this:

String wordOne = userInputSplit[0];
String wordTwo = null;
if (userInputSplit.length > 1){
    //This line will throw an error if you try to access something 
    //outside the bounds of the array
    wordTwo = userInputSplit[1];  
}
if (wordTwo !=null) {
    System.out.println("The apple is " + wordOne + " with " + wordTwo + " dots.");
} 
else {
    System.out.println("The apple is " + wordOne + " with no colored dots.");
}

Upvotes: 2

Reimeus
Reimeus

Reputation: 159754

You could enclose your print logic with a guard if statement:

if (userInputSplit.length > 1) {
  String wordOne = userInputSplit[0];
  String wordTwo = userInputSplit[1];
  ...
}

Upvotes: 2

Related Questions