当前位置:   article > 正文

java 动态实现数组增删(韩顺平)_scanner myscanner = new scanner(system.in);

scanner myscanner = new scanner(system.in);

一.简单的数组扩容

  1. int[] arr1 = {1,2,3};
  2. int[] arrNew = new int[arr1.length + 1];
  3. for (int i = 0; i < arr1.length; i++) {
  4. arrNew[i] = arr1[i];
  5. }
  6. arrNew[arr1.length] = 5;
  7. arr1 = arrNew;//将arrnew的地址传给arr1后,数组arr1将消失
  8. for (int i = 0; i < arr1.length + 1; i++) {
  9. System.out.println(arrNew[i]);
  10. }
  11. for (int i = 0; i < arr1.length; i++) {
  12. System.out.println(arr1[i]);
  13. }

二.连续进行数组扩容

不知道用户什么时候结束扩容,用do-while + break语句来实现

  1. Scanner myscanner = new Scanner(System.in);
  2. int[] arr = {1,2,3};
  3. do {
  4. int[] arrnew = new int[arr.length + 1];
  5. for (int i = 0; i < arr.length; i++) {
  6. arrnew[i] = arr[i];
  7. }
  8. arrnew[arrnew.length - 1] = myscanner.nextInt();
  9. arr = arrnew;
  10. for (int i = 0; i < arrnew.length; i++) {
  11. System.out.println(arrnew[i]);
  12. }
  13. System.out.println("是否继续输入");
  14. char key = myscanner.next().charAt(0);
  15. if (key == 'n') break;//输入n结束扩容
  16. }while (true);

三.数组删减

  1. int[] arr = {1,2,3};
  2. Scanner myscanner = new Scanner(System.in);
  3. do {
  4. int[] newarr = new int[arr.length - 1];
  5. for (int i = 0; i < newarr.length; i++) {
  6. newarr[i] = arr[i];
  7. }
  8. arr = newarr;
  9. char s = myscanner.next().charAt(0);
  10. if (newarr.length == 0 || s == 'n') break;//输入n或数组大小为0时结束缩减
  11. for (int i = 0; i < newarr.length; i++) {
  12. System.out.println(newarr[i]);
  13. }
  14. }while (true);

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/207180
推荐阅读
相关标签
  

闽ICP备14008679号