I am having a few problems in getting a method to work properly in Java. In the program I have created an array consisting of many different words of different length. The method I’m working on is supposed to read user input for wordlength, letter, and position, and Java will then print out any words matching these three parameters (for instance, if the user types wordlength 4, letter A and position 2, and words with length 4 containing the letter A at position 2 will be printed out).
Anyhow, the method I have created looks like this:
public static void inputMethod(int length, char letter, int position){
for (int index = 0; index < wordTable.length; index++) {
if (length == wordTable[index].length() && letter == wordTable[index].charAt(position) )
System.out.println(wordTable[index]); }
This method works fine for for some inputs, but for other inputs I get an error message such as this:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(Unknown Source)
at Wordarray.inputMethod(Wordarray.java:153)
at Wordarray.main(Wordarray.java:61)
If anyone could explain to me how I can fix this, I would greatly appreciate it! Like I said, I only get this message for certain inputs. For other inputs the program works just like it is supposed to.
If you have replaced
with
that is most likely not what you really want.
The better approach would be like this: