My sample Mid-term asks me to write a method that takes an array called origArr and returns a copy of it. The returned copy should have a specified length called len and if len is greater than origArr's length than the extra slots are filled with zero. The question also states that no functions of the array class can be used. When I print the new array it doesn't add the zero's to the extra slots. So far my code is:
public static void main(String[] args) {
int[] origArr = {1,2,3,4,5,6};
int len = 0;
int[] array = myCopyOf(origArr, len);
for (int i=0; i < array.length; i ) {
System.out.println(array[i]);
}
}
public static int[] myCopyOf(int[] origArr, int len) {
//declare new array//
int[] myCopyOf = new int[origArr.length];
//declare length should be equal to origArr' length//
len = origArr.length;
if (len > origArr.length) {
for (int i = 0; i < origArr.length; i ) {
myCopyOf[i] = origArr[i] 0;
}
}
return myCopyOf;
}
CodePudding user response:
In Java, primitives - int
is a primitive - always have a value; if they aren't initialized explicitly with a value they are assigned their default value, which for numeric primitives is zero.
This means that when you create a int[]
, all elements are 0
, so you don't have to do anything special - the extra elements are already 0
.
There are 2 bugs in your code.
First bug:
int[] myCopyOf = new int[origArr.length];
Should be:
int[] myCopyOf = new int[len];
Second bug: you should delete the if
and correct the loop termination condition:
for (int i = 0; i < origArr.length && i < len; i ) {
myCopyOf[i] = origArr[i];
}
which handles when len
is less or greater than the array's length.
Also, no need for the 0
.
CodePudding user response:
int[] myCopyOf = new int[origArr.length];
Here you create a new array with the same length as the original array. But your requirements say that the length must be what is specified by the len
parameter, so use that:
int[] myCopyOf = new int[len];
This will automatically fill in zeros when len
is greater than origArray.length
. You will need to be careful when origArray
is shorter, though. You can make a small modification to the for loop to fix that. I will leave the details as an exercise.