//已知有一个数组,/*数组里面的元素有a b c d e f y z,从控制台中随机输入一个字母,按照升序的顺序插入到该数组中并且遍历输出。*/public static void test1(){String [] str={"a","b","c","d","e","f","y","z"};String [] str1=new String[str.length+1];System.out.println("原来数组里面的元素");for (String s : str) {System.out.print(s+" ");}//赋值数组for(int i = 0;i<str.length;i++){str1[i] =str[i];}System.out.println("\n请输入要插入的元素:");Scanner sc = new Scanner(System.in);String name= sc.next();//找到需要插入的位置int index =0;for(int i = 0;i<str.length;i++){if(str[i].compareToIgnoreCase(name)>0){index = i;break;}}//元素往后移动for (int i =str1.length-1; i >index; i--) {str1[i] = str1[i-1];}//在指定位置插入新元素str1[index] = name;System.out.println("插入之后的数组是:");for (String s : str1) {System.out.print(s+" ");}}
运行结果如图所示:
欢迎关注公众号雄雄的小课堂: