Java Insert Data Note

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.