-1

I am trying to write a program that display's the user's input in reverse. I know that there are better ways to do this but let me make a long story short by saying my teacher is not the most understanding of individuals that being said here's what I got so far:

public static void main(String[] args) 
{
    String input;
    int len;

    input = JOptionPane.showInputDialog(null, "Please enter a string value: ");
    len = input.length();
    char[] txt = new char[len];
    for (int i = 0; i <= len; i++)
    {
        txt[i] = input.charAt(i);
    }
    for (int j = len; j >= 0; j--)
    {
        System.out.print(txt[j]);
    }
}

The error I keep receiving is as follows:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 at program.main(program.java:28)

It points to the line:

System.out.print(txt[j]);

I understand that the error is saying that I have exceeded the limits of the array I'm just not seeing how. Any help or input will be greatly appreciated. Thank You.

M A
  • 71,713
  • 13
  • 134
  • 174
Altros
  • 11
  • possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – njzk2 Nov 03 '14 at 22:04
  • 1
    As a side note, given the error you receive, I understand your teacher insisting on you getting this to work. Were I a teacher, I would expect a student to fully understand loops before starting to take shortcuts. – njzk2 Nov 03 '14 at 22:06

3 Answers3

3

Replace

for (int i = 0; i <= len; i++)

with

for (int i = 0; i < len; i++)

And

for (int j = len; j >= 0; j--) {

with

for (int j = len-1; j >= 0; j--) {

Array indexes are zero-based, and end at array length - 1.

M A
  • 71,713
  • 13
  • 134
  • 174
2

Please change the looping condition in your for 1st loop !

i <= len

to

i < len 

It goes from 0 ... n-1

Also you need to change initialization condition in 2nd loop

int j = len

to

int j = len-1

It goes from n-1 ... 0

StackFlowed
  • 6,664
  • 1
  • 29
  • 45
1

Iterate over the array from (length-1) to 0. Array [length] is resulting in the IndexOutOfBoundsException.

Example code:

for (int i = 0; i < len; i++){
    txt[i] = input.charAt(i);
}
for (int j = len-1; j >= 0; j--){
    System.out.print(txt[j]);
}
Rolf ツ
  • 8,611
  • 6
  • 47
  • 72
proko
  • 1,180
  • 1
  • 7
  • 14