存在一个数组,数组中的元素为 int[] array = {1, 3, 5, 7, 9, 11, 13, 15, 17, 0};
要求 :
1. 0是无效元素,仅占位使用
2. 当前数组中【有效元素】个数为9 需求
3.在该数组中的指定下标位置放入指定元素
/* 方法分析 固定格式: public static 返回值: void 无需返回值 方法名: insert 形式参数列表 三个: 数组 int[] array 位置 index 元素 value 方法声明 public staitc void insert(int[] array , int index , int value) {} */ class HomeWorkc { public static void main(String[] args) { int[] array = {1, 3, 5, 7, 9, 11, 13, 15, 17, 0}; int index = 7; int value = 6; insert(array , index , value); } /** * 该方法是在对应数组中指定位置插入指定数值 * * @param int[] arr 传入的数组 * @param int index 传入的数据的位置 * @param int value 传入的数据数值 */ public static void insert(int[] arr , int index , int value) { if (index < 0 || index > arr.length) { System.out.println("输入位置错误"); //return; 增加else模块,减少return } else { //新插入的元素位置: //1.在现有有效数字中间插入,此时就要求插入的位置index所对应的 //数组中下标为index的元素被腾空(复制到后面的下标中) //2.在现有有效元素的后面位置插入 //i的初始值是9,也是数组的有效元素的个数 //i-1对应的就是最后一个有效元素在数组中的下标 //最后一步移位的操作是 index = (i-1) //for循环中,从后往前移 for (int i = 9 ; i > index ; i--) {//i-1操作的是要被腾空的位置 arr[i] = arr[i-1]; } arr[index] = value; } for (int i = 0 ; i < arr.length ;i++) { System.out.println(arr[i]); } return; } }
原文:https://www.cnblogs.com/raising/p/12770779.html