韩顺平老师视频作业,
要求:实现动态的给数组添加元素效果,实现对数组扩容。例
import java.util.Scanner; public class ArrayAdd{ public static void main(String[] args){ //数组扩容 Scanner input = new Scanner(System.in); int[] arr = {1,2,3}; boolean add = false; do{ //int num =arr.length+1; int[] arrNew = new int[arr.length+1]; for(int i = 0;i < arr.length;i++){ arrNew[i] = arr[i]; //int num = i+1; } System.out.print("请输入数组arr要添加的数据:"); arrNew[arrNew.length-1] = input.nextInt(); arr = arrNew; System.out.println("数组arr扩容后的值是:"); for(int i = 0;i < arr.length;i++){ System.out.print(arr[i]+" "); } System.out.println("n添加成功,是否继续添加y/n"); char continuance = input.next().charAt(0); if(continuance == 'y' || continuance == 'Y'){ add = true; }else if(continuance == 'n' || continuance == 'N'){ add = false; }else{ System.out.println("输入错误,结束输入"); add = false; } }while(add); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)