I am unclear as to what this is asking me to do, and how I execute it, in reference to the int [] copyAndReplaceLessThan(int []a, int b) method. Any help would be greatly appreciated, thanks.
Test this method in main. Print both the original array and the returned array which the method, copyAndReplaceLessThan, returns. Since this method returns a value (an integer array), you need to “catch” the returned value in a local variable (of type int []) in the calling method (main).
For example: Assuming you pass the array “x” to the method and use array “y” to catch the returned value. Print x before you call the method and then print both x and y after calling the method.
public class ArrayExamples{
public static void swapInts(int a, int b){
int temp;
temp = a;
a = b;
b = temp;
}
public static void swapIntArrays(int [] a, int [] b){
int x;
for (int i=0; i<a.length; i++){
x = a[i];
a[i]=b[i];
b[i]=x;
}
}
public static void printArray(int[] a){
for(int i = 0; i < a.length; i++)
{
System.out.print(a[i] + " ");
}
System.out.println("");
}
public static void main(String args[]){
int [] one ={3,4};
int [] two ={7,8};
printArray(one);
printArray(two);
swapIntArrays(one,two);
printArray(one);
printArray(two);
System.out.println();
int [] x ={3,45,17,2,-1,44,9,23,67,2,-6,-23,-100,12,5,1212};
int b = 12;
printArray(x);
replaceLessThan(x,b);
printArray(x);
printArray(x);
copyAndReplaceLessThan(x,b);
printArray(x);
printArray(y);
}
public static void replaceLessThan(int []a, int b){
for(int i=0; i < a.length; i++){
if(a[i] < b){
a[i] = b;
}
else{
a[i] = a[i];
}
}
}
public static int[] copyAndReplaceLessThan(int []a, int b){
int []x = a;
int[]y = x;
for(int i=0; i < a.length; i++){
if(a[i] < b){
a[i] = b;
y[i] = b;
}
else{
a[i] = a[i];
y[i] = a[i];
}
}
return y;
}
}
Some problems:
You're supposed to leave the original array unaltered, yet you're setting its elements with
a[i] = b;
And there's no point to doing this
a[i] = a[i];
as you're just resetting the value to itself.
But your biggest problem is that you're not creating a new array, as you're supposed to. Instead, your "new" array ( y
) is referring to the original one ( a
), and therefore any changes to y
are actually being made in the original.
I also recommend that you either test or try a
for null
ness.
public static int[] copyAndReplaceLessThan(int[] a, int b)
{
int[] x = a.clone();
for (int i = 0; i < x.length; i++)
{
if (x[i] < b)
{
x[i] = b;
}
}
return x;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.