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.");
}
Could just do something easy like this: