我寫了一個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);
}
}
}
現在程序的長度大於或等於串工作正常,到5,但如果我給長度爲4作爲輸入的字符串,我得到一個異常的ArrayIndexOutOfBounds 。可能是什麼問題呢?
哪條線不會例外拋出? –
不,這個算法肯定不適用於長度大於或等於5的所有字符串(提示:對於50%) - 並且實際上對於小於5的字符串是正確的。只要想一想你的算法的執行情況testcases,你肯定會看到自己的問題 – Voo