在數組中插入元素


 1 /* 5. 有如下歌曲數組 
 2 String[] musics = new String[]{"Island","Ocean","Pretty","Sun"};
 3 //這是按照字母順序排好序的 字符串數組
 4 
 5 現在要往里面插入新的英文歌曲,
 6 按照首字母排序插入到指定的位置
 7 
 8 提示: musics[i].compareToIgnoreCase(music) > 0
 9 上面這個方法是比較字符串的方法, 
10 如果前面的值大返回1,如果后面的大於前面的,返回-1,或者等於前面的,返回0
11 
12 例如 “Haha".compareToIgnoreCase("Aha")  是比較  haha 字符串 和 aha字符串 (此方法自動忽略大小寫)
13  h 比 a 大, 所以返回 是 1, (根據字母表順序)*/
14 
15  import java.util.*;
16  class five{
17      public static void main(String[] args) {
18         Scanner sc = new Scanner(System.in);
19         String[] musics = new String[]{"Island","Ocean","Pretty","Sun"};
20         int incre = 1; //容量增加量  
21         String[] a = new String[musics.length+incre];//新數組  
22         System.arraycopy(musics, 0, a, 0, musics.length);//將musics數組內容復制新數組a  
23         System.out.println("請插入新的英文歌曲");
24         String name = sc.nextLine();
25         a[a.length-1] = name;
26 
27         musics = a;   //改變引用  
28 
29         int count = 0;
30         for (int i = 0; i<musics.length-1 ;i++ ) {
31              if (musics[i].compareToIgnoreCase(name)>0) {
32                    count++;
33              }else {
34                  musics[musics.length-1] = name;
35              }
36          }
37         for (int i = musics.length-1 ;i> = 0 ;i-- ) {
38              if (i>musics.length-count-1) {
39                  musics[i] = musics[i-1];
40              }
41          }
42          musics[musics.length-count-1]=name;
43          System.out.println("添加成功:");
44          for (String i:musics) 
45              System.out.println(i);        
47      }
48  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM