一、数组的扩容
package com.jun.demo01;
import java.util.Scanner;
public class demo12 {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3};
//创建一个用户输入
Scanner scanner = new Scanner(System.in);
do {
int[] arr2 = new int[arr1.length + 1];
System.out.println("请输入你要添加的元素");
int scn = scanner.nextInt();
for (int i = 0; i < arr1.length; i++) {
arr2[i] = arr1[i];
}
arr2[arr2.length - 1] = scn;
arr1 = arr2;
//判断用户是否继续输入
System.out.println("是否继续添加元素");
char c = scanner.next().charAt(0);
if (c == 'y') {
break;
}
} while (true);
//遍历数组
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i]);
}
}
}
?二、数组缩减
package com.jun.demo01;
import java.util.Scanner;
public class demo13 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4,5};
Scanner sc = new Scanner(System.in);
do{
int[] arrNew = new int[arr.length - 1];
for(int i = 0; i < arrNew.length; i++){
arrNew[i] = arr[i];
}
arr = arrNew;
if(arr.length < 2){
System.out.println("数组元素个数为1,不能删除");
break;
}
System.out.print("数组的元素个数为"+arrNew.length+"是否继续删除: ");
char c1 = sc.next().charAt(0);
if (c1 == 'n'){
break;
}
} while(true);
}
}
?
|