数组的增删改查
public static void main(String[] args) { int[] arr = new int[]{10,20,30,22,15}; System.out.println(Arrays.toString(arr)); // System.out.println(Arrays.toString(insert(arr))); // System.out.println(Arrays.toString(insertT(arr))); //System.out.println(Arrays.toString(delete(arr))); //System.out.println(Arrays.toString(change(arr))); System.out.println((select(arr))); }
//特定位置增加单个元素
private static int[] insert(int[] arr){ Scanner scan = new Scanner(System.in); System.out.println("插入位置"); int index = scan.nextInt(); int digits = arr.length; if(index>=digits || index<0){ System.out.println("越界"); } System.out.println("插入的值"); int num = scan.nextInt(); int[] newArr = new int[arr.length+1]; for (int i = 0; i < index; i++) { newArr[i] = arr[i]; } newArr[index]=num; for (int j = index; j < arr.length; j++) { newArr[j+1] = arr[j]; } arr = newArr; return arr; }
//尾部追加
private static int[] insertT(int[] arr){ Scanner scan = new Scanner(System.in); System.out.println("插入的值"); int num = scan.nextInt(); int[] newArr = new int[arr.length+1]; for (int i = 0; i < arr.length; i++) { newArr[i]=arr[i]; } newArr[arr.length]=num; arr=newArr; return arr; }
//删除指定位置元素
private static int[] delete(int[] arr){ Scanner scan = new Scanner(System.in); System.out.println("删除哪一个位置的值"); int index = scan.nextInt(); int delight = arr.length; if (index>=delight || index<0){ System.out.println("越界"); } for (int i = index; i <arr.length-1; i++) { arr[i] = arr[i+1]; } int[] newArr = new int[arr.length-1]; for (int j = 0; j <arr.length-1 ; j++) { newArr[j]=arr[j]; } arr = newArr; return arr; }
//改动指定位置的值
private static int[] change(int[] arr){ Scanner scan = new Scanner(System.in); System.out.println("输入改动的位置"); int index = scan.nextInt(); int delight=arr.length; if (index>=delight || index<0){ System.err.println("越界"); } System.out.println("输入改动值"); int num = scan.nextInt(); arr[index]=num; return arr; }
//查找指定位置的值
private static int select(int[] arr){ Scanner scan = new Scanner(System.in); System.out.println("查哪"); int index = scan.nextInt(); int delight = arr.length; if (index>=delight || index<0){ System.err.println("越界"); } int a = arr[index]; return a; }