我编写了一个java程序来反转字符串的内容并显示它们.
这是代码..
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在程序适用于长度大于或等于5的字符串.但是如果我给出一个长度为4的字符串作为输入,我得到一个ArrayIndexOutOfBounds异常.可能是什么问题呢?
问题不在于输入长度为4,而是长度4是偶数长度,因此您的停止条件永远不会发生.也就是说,frontpos 永远不等于rearpos偶数长度的字符串.
而应该只是确保frontpos是少比rearpos,改变while(frontPos!=rearPos)到while(frontPos < rearPos)应该明确的事情了.