1. An example of how to insert an element into an array.
Import java.util.*;
public class Test01 {
public static void Main (string[] args) {
Int[]list = new Int[5]; An array of length 5
Scanner input = new Scanner (system.in);
System.out.println ("Assign a value to an array:");
for (int i=0;i<list.length;i++) {//input Insert Data
List[i]=input.nextint ();
}
Arrays.sort (list); Sort
System.out.println ("Please enter Number:");
int num = Input.nextint ();
int[] Nums = new int[list.length+1]; Make the new array equal to the old array and one more grid
for (int i=0;i<list.length;i++) {
Nums[i] = List[i];
}
int index = nums.length+1;//Save the inserted data location
Record the location of the newly inserted data
for (int i=0;i<nums.length;i++) {
if (nums[i]>num) {
Index=i;
Break
}
}
Element move back
for (int i=nums.length-1;i>index;i--) {
nums[i]=nums[i-1];//the element that starts with the subscript moves back one position
}
Nums[index]=num; Inserting data
for (int i=0;i<nums.length;i++) {
System.out.println (nums[i]+ "\ t"); Output new Array
}
}
}
Results such as:
Thank you!
Java Insert Data Note