Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string reverse problem

Tags:

java

i have written a java program to reverse the contents of the string and display them.

here is the code..

import java.util.*;
class StringReverse
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a string to be reversed :");
        String input = in.next();  
        char[] myArray = new char[input.length()];
        myArray = input.toCharArray();
        int frontPos=0,rearPos=(myArray.length)-1;
        char tempChar;
        while(frontPos!=rearPos)
        {
            tempChar=myArray[frontPos];
            myArray[frontPos]=myArray[rearPos];
            myArray[rearPos]=tempChar;
            frontPos++;
            rearPos--;
        }
        System.out.println();
        System.out.print("The reversed string is : ");
        for(char c : myArray)
        {
            System.out.print(c);
        }

    }
}

Now the program works fine for strings of length greater than or equal to 5. But if I give a string of length 4 as input, I get an ArrayIndexOutOfBounds Exception. What could be the problem?

like image 945
kunaguvarun Avatar asked Aug 05 '26 08:08

kunaguvarun


1 Answers

The issue isn't that the input is of length 4, but that the length 4 is an even length, so your stopping condition never hits. That is, frontpos never equals rearpos for even length strings.

You should instead just make sure that frontpos is less than rearpos, changing while(frontPos!=rearPos) to while(frontPos < rearPos) should clear things up.

like image 192
Mark Elliot Avatar answered Aug 06 '26 21:08

Mark Elliot