对数组a[] = {1,2,3,4}进行扩容;
在扩容一个数值成功后询问是否继续进行扩容;
回答为Y则继续可以输入数值;回答为N则退出程序.
import java.util.Scanner;
public class array {
public static void main(String[] args) {
//对数组 int[] a = {1,2,3,4}进行扩容
Scanner input= new Scanner(System.in);
char answer;
int[] a = {1,2,3,4};
do {
int[] b = new int[a.length + 1];
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
System.out.println("请输入要添加的数字:");
int num = input.nextInt();
b[b.length - 1] = num;
a = b;
System.out.println("添加后的数组为:");
for (int i = 0; i < a.length; i++){
System.out.print(a[i]);
}
System.out.println();
System.out.println("添加成功!是否继续添加?Y/N");
answer = input.next().charAt(0);
} while (answer =='Y');
//输出添加成功,并询问是否继续添加
}
}