指定位置插入指定元素
c. 在指定位置插入指定元素【难点】
存在一个数组,数组中的元素为
int[] array = {1, 3, 5, 7, 9, 11, 13, 15, 17, 0};
要求
1. 0是无效元素,仅占位使用
2. 当前数组中【有效元素】个数为9
需求
在该数组中的指定下标位置放入指定元素
代码运行中是否有需要考虑的异常情况?
越界问题
用户指定的下标位置,超出的有效位置
需要在代码中进行参数合法性判定!!!
方法分析:
固定格式:
public static
返回值类型:
void:
OK选择!!!
int:
操作成功返回1,失败返回-1
boolean: [选择]
添加成功返回true,运行失败返回false
方法名:
add 这里是一个添加操作
形式参数列表:
1. 添加数据的数组
2. 指定添加的下标位置
3. 指定添加的数据
(int[] arr, int index, int insert)
方法声明:
public static boolean add(int[] arr, int index, int insert)
package com.qfedu.a.homework;
/**
* 在数组中指定下标位置添加元素
* @author Anonymous
*
*/
public class HomeWork3 {
public static void main(String[] args) {
int[] array = {1, 3, 5, 7, 9, 11, 13, 15, 17, 0};
boolean ret = add(array, 5, 100);
if (ret) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
} else {
System.out.println("方法运行失败!!!");
}
}
/**
* 在数组arr中指定下标位置,添加指定元素
*
* @param arr 添加元素是数组
* @param index 指定添加数据的下标位置
* @param insert 指定添加的数据
* @return 方法运行成功完成添加操作,返回true,否则返回false
*/
public static boolean add(int[] arr, int index, int insert) {
// 参数合法性判断
if (index < 0 || index > arr.length - 1) {
System.out.println("Input Parameter is Invalid!");
// 用户传入参数不合法&