McNasty49 McNasty49 -4 years ago 74
Java Question

Printing two arrays inside of a third array that has the same combined length as the first two

What I need to do is create a third dynamic array (I think I did) that combines the length of the first two and then prints out the contents of those arrays as the output of the third array.

Example:

Array 1:
1
4
2
6
0

Array 2:
3
6
2
1
5

Array 3:
1
4
2
6
0
3
6
2
1
5

This is what I have so far:

import javax.swing.*;

public class DynamicArray
{
public static void main(String[] args)
{
// User Input - Array length
int arrayLength;
arrayLength = Integer.parseInt(JOptionPane.showInputDialog("Enter Array length:"));

// First dynamic array
int[] dynArray1;
dynArray1 = new int[arrayLength];

for (int i = 0; i < dynArray1.length; i++)
{
dynArray1[i] = (int) (Math.random() * 10);
}

System.out.println("First Array:");

for (int j = 0; j < dynArray1.length; j++)
{
System.out.println(dynArray1[j]);
}

// Second dynamic array
int[] dynArray2;
dynArray2 = new int[arrayLength];

for (int i = 0; i < dynArray2.length; i++)
{
dynArray2[i] = (int) (Math.random() * 10);
}

System.out.println("Second Array:");

for (int j = 0; j < dynArray2.length; j++)
{
System.out.println(dynArray2[j]);
}

// Third dynamic array
int thirdArrayLength = dynArray1.length + dynArray2.length;
int[] dynArray3;
dynArray3 = new int[thirdArrayLength];

for (int i = 0; i < dynArray3.length; i++)
{

}
}
}


I would just print the first and second but I think that would be cheating and it isn't what my assignment is asking for. I was going to for loop Array1 and Array2 and println the results. I'm not exactly sure how I should go about it though. Any help would be appreciated.

EDIT: This has been solved! Below is the code:

/* Third dynamic array */
int thirdArrayLength = dynArray1.length + dynArray2.length;
int[] dynArray3;
dynArray3 = new int[thirdArrayLength];

for (int i=0; i < dynArray1.length; i++) {
dynArray3[i] = dynArray1[i];
}
for (int i=0; i < dynArray2.length; ++i) {
dynArray3[i + dynArray1.length] = dynArray2[i];
}

System.out.println("Third Array:");

for (int i=0; i < dynArray3.length; ++i) {
System.out.println(dynArray3[i]);
}

Answer Source

One option is to just iterate over the first two arrays and populate the third array:

for (int i=0; i < dynArray1.length; i++) {
    dynArray3[i] = dynArray1[i];
}
for (int i=0; i < dynArray2.length; ++i) {
    dynArray3[i + dynArray1.length] = dynArray2[i];
}

// then print out the third array
for (int i=0; i < dynArray3.length; ++i) {
    System.out.println(dynArray3[i]);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download