数组动态扩容:
package com; import java.lang.String; import java.util.Scanner; public class Linghu { public static void main(String []args){ int arr[]={1,2,3}; Scanner myScanner = new Scanner(System.in); do{ System.out.println("请输入需要添加的元素"); int arrNew[]=new int[arr.length+1]; int addNum=myScanner.nextInt(); for (int i=0;i<arr.length;i++){ arrNew[i]=arr[i]; } arrNew[arrNew.length-1]=addNum; arr=arrNew; System.out.println("=======元素输出为:"); for (int j=0;j<arr.length;j++){ System.out.print(arr[j]+"\t"); } System.out.println("是否继续添加元素?y/n"); char key=myScanner.next().charAt(0); if(key=='n') break; }while(true); } }
数组动态缩减:
package com; import java.lang.String; import java.util.Scanner; public class Linghu { public static void main(String []args){ int arr[]={1,2,3}; Scanner myScanner = new Scanner(System.in); do{ //System.out.println("输入需要添加的新元素:"); int arrNew[]= new int [arr.length-1]; //int addNum=myScanner.nextInt(); for (int i=0;i<arr.length-1;i++){ arrNew[i]=arr[i]; } //arrNew[arrNew.length-1]=addNum; arr=arrNew;//arr的指针指向arrNew System.out.println("缩减后的数组元素为:"); for (int j=0;j<arr.length;j++){ System.out.print(arr[j]+"\t"); } System.out.println("是否需要缩减元素?Y/N"); char key=myScanner.next().charAt(0); if(key=='n') break; }while(true); } }