Computer Science Canada help - reversing string input |
Author: | whoareyou [ Tue Apr 19, 2011 3:09 pm ] | ||||
Post subject: | help - reversing string input | ||||
This "test" program is supposed to output a string that was inputted in reverse order. I can get it working, except it won't show the first letter. For example, if the string I input is "Hello", it outputs "olle". That's the first problem. The second problem is that when I set up a for loop to count from the last letter to the first, it displays a weird error message.
This is the actual code.
Any help/suggestions would be appreciated ![]() |
Author: | DemonWasp [ Tue Apr 19, 2011 3:14 pm ] |
Post subject: | RE:help - reversing string input |
Java's Strings are indexed from 0. This means that the "first" character is 0, the second is 1, and the nth character is at index (n-1). Your loop seems to be working on the assumption that it can access index (n) of an n-characters-long string, which it can't -- it can only access up to index (n-1). Edit: That's a pretty self-explanatory error message. If you read it, it's telling you that your String Index is Out of Bounds, and that caused an Exception. It tells you the exact line where it happened, and it even mentioned that you were looking at index 5. Given as the String is "Hello", index 0 is 'H', index 1 is 'e', ..., index 5 is out of bounds. |