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?
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,
frontposnever equalsrearposfor even length strings.You should instead just make sure that
frontposis less thanrearpos, changingwhile(frontPos!=rearPos)towhile(frontPos < rearPos)should clear things up.