I want to merge 2 Stirng arrays the first one is merged okay but the second one keeps having null values even though it isn't empty no errors just wrong values what is the problem here?
public class Q4 {
public static void main(String[] args){
String array1[] = new String[]{"Ahmad", "Adam"};
String array2[] = new String[]{"Mick", "Ali"};
int n1 = array1.length;
int n2 = array2.length;
String []array3 = new String[n1 n2];
for(int i = 0; i < n1; i )
array3[i] = array1[i];
for(int i = n1; i<n2; i ) {
int j = 0;
array3[i] = array2[j ];
}
for(int i = 0; i<array3.length; i )
System.out.print(array3[i] " ");
}
}
the output should be
Ahmad Adam Mick Ali
but this is what I get
Ahmad Adam null null
CodePudding user response:
Your Second loop's i value is n1 size(2).and loop will continue before n2 size(2).that's why value not added.
Solution: U need add value after 1st array. If you will Store value from 1st array size ,then it will store value perfectly.
public class Q4 {
public static void main(String[] args){
String array1[] = new String[]{"Ahmad", "Adam"};
String array2[] = new String[]{"Mick", "Ali"};
int n1 = array1.length;
int n2 = array2.length;
String []array3 = new String[n1 n2];
for(int i = 0; i < n1; i ){
array3[i] = array1[i];
}
for(int i = 0; i<n2; i ) {
array3[n1 ] = array2[i];
}
for(int i = 0; i<array3.length; i )
System.out.print(array3[i] " ");
}
}
CodePudding user response:
for(int i = n1; i<n2; i ) {
the condition inside the second for loop is wrong. As it is now you are starting from size of first array (2) to size of second array (2)
what you want should be
for(int i = n1; i<n2 n1; i ) {
also you are declaring int j
inside the for loop which means j is reset each loop, move its definition outside of the loop or better yet replace it with
i-n1
CodePudding user response:
In the second for loop I should've used i<array3.length instead of i<n2 since i=n1 and n2=n1 so for loop wasn't even excuted