import java.util.Scanner; public class InsertNum { public static void main(String[] args) { // 思路:創建2個數組,把第一個數組的元素遍歷到第二個數組中,然后把要插入的元素與數組中的元素進行比較。 int[] arr1 = new int[] { 1, 4, 5, 7, 9 }; int index = arr1.length; System.out.println("請輸入一個數"); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr2 = new int[arr1.length + 1]; System.out.println("插入元素之前:"); // 把第一個數組的元素遍歷到第二個數組中 for (int i = 0; i < arr1.length; i++) { arr2[i] = arr1[i]; System.out.print(arr2[i] + " "); } System.out.println(); // 把要插入的元素與數組中的元素進行比較,如果要插入的元素小於數組中的元素,把當前的下標給index. for (int j = 0; j < arr2.length; j++) { if (n < arr2[j]) { index = j; break; } } // 依次把index之后的數組的元素的值。給它的下一個下標。 for (int x = arr2.length - 1; x > index; x--) { arr2[x] = arr2[x - 1]; } // 把要插入的元素的值賦值給index. arr2[index] = n; System.out.println("插入元素之后:"); // 遍歷插入元素后的數組 for (int y = 0; y < arr2.length; y++) { System.out.print(arr2[y] + " "); } } }