程序是實現(xiàn)一個純字母字符串排序,如:sort("acb") 返回"abc".問題是:? 當(dāng)測試字符串為“acb”時可以正確顯示排序結(jié)果,? 當(dāng)測試字符串為”dbca“時卻顯示:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1? at Sort.sort1(Sort.java:38)? at Sort.main(Sort.java:9)請大蝦幫忙看看怎么出錯了!現(xiàn)在,源代碼如下:
1 import java.util.Scanner;
2 public class Sort
3 {
4 public static void main(String[] args)
5 {
6 Scanner sca = new Scanner(System.in);
7 System.out.println("請輸入一個字符串:");
8 String s = sca.next();
9 System.out.println("排序前的字符串為: " + s + "\n" +
10 "排序后的字符串為: " + sort1(s));
11
12 }
13
14 public static String sort1(String s){
15 //插入排序
16 char[] array = s.toCharArray();
17 for(int i = 1;i < s.length();i++){
18 char temp = array[i];
19 int j = i - 1;
20 //大的字符后移操作
21 while(array[j] > temp && j >= 0){
22 array[j + 1] = array[j];
23 j--;
24 }
25 //插入操作
26 array[j + 1] = temp;
27 }
28
29 StringBuffer ss = new StringBuffer();
30 ss.append(array);
31 return ss.toString();
32 }
33 }
?
?
添加回答
舉報
0/150
提交
取消