java第八章 string char数组排序 插入

    xiaoxiao2022-06-30  101

    <span style="font-size:18px;"> String[] musics = new String[]{"Island","Ocean","Pretty","Sun"}; String[] newMusics = new String[musics.length+1];//新歌曲数组 String music = ""; //保存用户输入的歌曲名称 int index = musics.length; //保存新歌插入位置 //输出插入前的结果 System.out.print("插入前的数组为:"); for(int i = 0; i < musics.length ; i++){ System.out.print(musics[i]+" "); } //将数组musics中的元素复制到新歌曲数组newMusics中 for(int i = 0; i < musics.length; i++){ newMusics[i] = musics[i]; } //输入歌曲名称 Scanner input = new Scanner(System.in); System.out.print("\n请输入歌曲名称:"); music = input.nextLine(); //找到新元素的插入位置 for(int i = 0; i < musics.length; i++){ //123456789 if(musics[i].compareToIgnoreCase(music) > 0){ index = i; break; } } //元素后移 for(int i = newMusics.length-1; i > index; i--){ newMusics[i] = newMusics[i-1]; //index下标开始的元素后移一个位置 } newMusics[index] = music; //新元素放在index的位置 //输出插入后的结果 System.out.print("插入后的数组为:"); for(int i = 0; i < newMusics.length; i++){ System.out.print(newMusics[i]+" "); } *********************************************************************************************** //字符排序 char[] chars = new char[9]; chars[0] = 'a'; chars[1] = 'c'; chars[2] = 'u'; chars[3] = 'b'; chars[4] = 'e'; chars[5] = 'p'; chars[6] = 'f'; chars[7] = 'z'; System.out.print("原字符序列:"); for(int i = 0; i < chars.length; i++){ System.out.print(chars[i] + " "); } Arrays.sort(chars); //对数组进行升序排序 System.out.print("\n升序排序后:"); for(int i = 0; i < chars.length; i++){ System.out.print(chars[i] + " "); } //实现插入字符 int index = chars.length; //保存新增成绩插入位置 char ch='m'; System.out.println("\n待插入的字符是: "+ch); //找到新元素的插入位置 for(int i = 0; i < chars.length; i++){ if(ch < chars[i]){ index = i; break; } } //元素后移 for(int j = chars.length-1; j > index; j--){ chars[j] = chars[j-1]; //index下标开始的元素后移一个位置 } chars[index] = ch;//插入数据 System.out.println("插入字符的下标是:"+index); System.out.print("插入后的字符序列是: "); for (int k = 0; k < chars.length; k++) { // 循环输出目前数组中的数据 System.out.print(chars[k] + " "); }</span>
    转载请注明原文地址: https://ju.6miu.com/read-1126167.html

    最新回复(0)