解決數組想刪除那個元素就刪除哪一個元素

解決數組不可變之刪除某一個元素

解決數組想刪除那個元素就刪除哪一個元素
生活就是如此簡單

在這裏插入圖片描述



package 數組使用;

 

import
java.util.Arrays;

import
java.util.Scanner;

 

//刪除數組中的某一個元素

public class TestDe {

    public static void main(String[] args) {

         int[] a = new int[] { 1, 2, 3, 4, 5, 6 };

         System.out.println("原數組爲:" + Arrays.toString(a));

         // 要刪除元素的下標

         int n;

         System.out.print("我想刪除第n個元素:n=");

         n = new
Scanner(System.in).nextInt();

         int[] newArray = new int[a.length - 1];

         for (int i = 0; i < newArray.length; i++) {

             if (i < n - 1) {

                  newArray[i] = a[i];

             } else {

                  newArray[i] = a[i + 1];

             }

         }

         a = newArray;

         System.out.println("刪除第" + n + "個元素後爲" + Arrays.toString(a));

 

    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章