数组中元素的增加
//实现动态的给数组添加元素效果,实现对数组扩容
import java.util.Scanner;
public class ArrayDemo5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] a = {1,2,3};
do {
int count = scanner.nextInt();//扩容个数
int[] a1 = new int[a.length+count];
for (int i = 0; i < a.length; i++) {
a1[i] = a[i];
}
for (int i = 0; i < count; i++) {
System.out.println("请输入数字");
int num = scanner.nextInt();//扩容数字
a1[a.length+i] = num;
}
a = a1;
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
System.out.println("是否继续添加 y/n");
char key = scanner.next().charAt(0);
if (key == 'n') {
break;
}
}while (true);
System.out.println("你退出了");
}
}
数组中元素的缩减:缩减最后一个
import java.util.Scanner;
//实现数组的缩减
public class ArrayDemo6 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] a = {1,2,3,4,5,6};
do {
int[] a1 = new int[a.length-1];
for (int i = 0; i < a.length-1; i++) {
a1[i] = a[i];
}
a = a1;
System.out.println("==缩减后的a");
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
System.out.println("是否要继续缩减 y/n");
char key = scanner.next().charAt(0);
if (key == 'n') {
break;
}
if (a.length-1 == 0) {
break;
}
}while (true);
System.out.println("您退出了程序");
}
}