Array addition/expansion
- Requirements: dynamic to add elements to the array effect, to achieve the array expansion. ArrayAdd.java
- The original array is allocated statically
Int [] arr = {1, 2, 3}
- Added element
4
, 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 traversearr
Array, in turnarr
Copy the element toarrNew
An array of
4. Assign 4 toarrNew[arrNew.length - 1] = 4;
the4
Assigned toarrNew
The last element
5. Letarr
Point to thearrNew ; arr = arrNew;
So the originalarr
An 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
- 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
- To create a
Scanner
Can accept user input - Because when does the user quit, not sure, use
do-while + break
To 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