JAVA array inserts and deletes the instance code of the specified element, java instance
Today I learned the Java array and wrote the insertion and deletion of the array. I am a little white and can't write it to others. Please ignore it. If there are any mistakes, please point it out;
/** Insert the array at the specified position to the array */import java. util. *; public class ArrayInsert {public static void main (String [] args) {System. out. println ("Enter five numbers on the keyboard:"); int [] array = new int [10]; Limit SC = new limit (System. in); // input the number of for (int I = 0; I <array. length-5; I ++) {array [I] = SC. nextInt ();} // traverses the array System. out. print ("original array:"); for (int a: array) {System. out. print ("" + a);} // Number of inserts to a specified position System. out. println ("\ n please input Insert Location: valid position 0 -----" + (array. length-1); int index = SC. nextInt (); System. out. println ("\ n enter the inserted value -----"); int num = SC. nextInt (); // call the static function index // traverse the inserted array System. out. println ("array traversal after inserting elements:"); Insert (index, num, array); for (int I = 0; I <array. length; I ++) {System. out. print ("" + array [I]) ;}// Insert data to the specified position of the array using the public static int [] Insert (int index, int num, int a []) Method {// If an element exists, the element after the index moves one to the back, for (int a [I] = a [I-1];} a [index] = num; return ;}}
// Delete the number at the specified position of the array. Import java. util. *; public class ArrayDelete {public static void main (String args []) {System. out. println ("Enter five numbers on the keyboard:"); int [] array = new int [10]; Limit SC = new limit (System. in); // input the number of for (int I = 0; I <array. length-5; I ++) {array [I] = SC. nextInt ();} // traverses the array System. out. print ("original array:"); for (int a: array) {System. out. print ("" + a);} // Delete the number System at the specified position. out. println ("\ n enter the location you want to delete: the range is 0 ---" + (array. length -1); int index = SC. nextInt (); delete (index, array); // call the delete method // traverse System after deletion. out. println ("traversal after deletion:"); for (int I = 0; I <array. length; I ++) {System. out. print ("" + array [I]) ;}} public static int [] delete (int index, int array []) {// Based on the deletion index, move the value behind the array one forward (int I = index; I <array. length; I ++) {if (I! = Array. length-1) {array [I] = array [I + 1];} else {// process the last digit exceeding conditions array [I] = array [I];} return array ;}}
The example code for inserting and deleting a specified Element in the above JAVA code is all the content shared by Alibaba Cloud. I hope you can give us a reference and support for more.