Array addition/expansion

  • Requirements: dynamic to add elements to the array effect, to achieve the array expansion. ArrayAdd.java
  1. The original array is allocated staticallyInt [] arr = {1, 2, 3}
  2. Added element4, directly at the end of the arrayArr = {1, 2, 3, 4}

    ArrayAdd02.java
  • Thought analysis

    1. Define the initial arrayInt [] arr = {1,2,3}// subscript 0-2

    Define a new arrayint[] arrNew = new int[arr.length+1];

    3. The traversearrArray, in turnarrCopy the element toarrNewAn array of

    4. Assign 4 toarrNew[arrNew.length - 1] = 4;the4Assigned toarrNewThe last element

    5. LetarrPoint to thearrNew ; arr = arrNew;So the originalarrAn array isThe destruction
  • Code implementation:
	  int[] arr = {1.2.3};
      int[] arrNew = new int[arr.length + 1];
      // Iterate over the ARR array, copying the arR elements into the arrNew array in turn
      for(int i = 0; i < arr.length; i++) {
          arrNew[i] = arr[i];
      }
      // Assign 4 to arrNew's last element
      arrNew[arrNew.length - 1] = 4;
      // Set arR to arrNew,
      arr = arrNew;
      // output arr to see the effect
      System.out.println("==== Elements after arR expansion ====");
      for(int i = 0; i < arr.length; i++) {
          System.out.print(arr[i] + "\t");
      }
Copy the code



  1. You can perform the following operations to determine whether to continue adding the vm. If the vm is added successfully, do you want to continue?y/n
  1. To create aScannerCan accept user input
  2. Because when does the user quit, not sure, usedo-while + breakTo control the

Code implementation:

	Scanner myScanner = new Scanner(System.in);
	// Initialize the array
	int[] arr = {1.2.3};
	
	do {
		int[] arrNew = new int[arr.length + 1];
		// Iterate over the ARR array, copying the arR elements into the arrNew array in turn
		for(int i = 0; i < arr.length; i++) {
			arrNew[i] = arr[i];
		}
		System.out.println("Please enter the element you want to add.");
		int addNum = myScanner.nextInt();
		// Assign addNum to the last element of arrNew
		arrNew[arrNew.length - 1] = addNum;
		// Set arR to arrNew,
		arr = arrNew;
		// output arr to see the effect
		System.out.println("==== Elements after arR expansion ====");
		for(int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + "\t");
		}
		// Ask the user whether to continue
		System.out.println("Do I want to continue adding y/n?");
		char key = myScanner.next().charAt(0);
		if( key == 'n') { // If n is entered, end
			break; }}while(true);
	
	System.out.println("You signed out of adding...");
Copy the code