string reverse problem
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, 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.
Would probably be easier to write with only one counter.
for(int i = 0; i < myArray.length; i++) {
char temp = myArray[i];
myArray[i] = myArray[myArray.length - i - 1];
myArray[myArray.length - i - 1] = temp;
}
String reversed = new String(myArray);
Why are you making the logic so complicated. It can easily be done as:
char temp[] = new char[str.length()];
int k = 0;
for(int i = str.length()-1 ; i >= 0 ; i--)
{
temp[k] = str.charAt(i);
k++;
}
System.out.println(new String(temp));
public String reverse(String str)
{
String rev = " ";
for (int i = 0 ; i < str.length(); i++)
{
rev = str.charAt(i) + rev;
}
return rev.trim();
}
Input:
December
Output:
rebmeceD
精彩评论