StringIndexOutOfBoundsException on my assignment for AP Computer Science A

57 Views Asked by At

I'm working on an assignment (java) for my AP Computer Science A class where I have to combine to strings alternating by letter in reverse order together. For example, balloon and atrophy outputs ynhopoolrltaab. However, I keep receiving this error message. Can anyone help? Here is my code:

I'm using a for loop as that is the main idea for the lesson I am on in the class right now but no matter what I try inside of the parenthesis, I still receive the same error.

2

There are 2 best solutions below

0
J Willis On

The reason for this particular error is that you're setting your variable i equal to the sum of the length of both your input strings which results in the substring method trying to access an index that is beyond the length of either input string.

To solve this error, set i equal to the length of just one of your input strings.

1
Reilas On

"... However, I keep receiving this error message. Can anyone help? Here is my code:

I'm using a for loop as that is the main idea for the lesson I am on in the class right now but no matter what I try inside of the parenthesis, I still receive the same error. ..."

Iterate on the length of just one word.
The i value will be the same for both String values.

Here is an example.

StringBuilder a, b, s = new StringBuilder();
a = new StringBuilder("atrophy").reverse();
b = new StringBuilder("balloon").reverse();
for (int i = 0, n = a.length(); i < n; i++)
    s.append(a.charAt(i)).append(b.charAt(i));

Output

ynhopoolrltaab

Here are the links to the Java tutorials.