[英]Returning Array Method
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.我不清楚这要求我做什么,以及我如何执行它,参考int [] copyAndReplaceLessThan(int []a, int b)方法。 Any help would be greatly appreciated, thanks.
任何帮助将不胜感激,谢谢。
Test this method in main.在 main.c 中测试此方法。 Print both the original array and the returned array which the method, copyAndReplaceLessThan, returns.
打印原始数组和方法 copyAndReplaceLessThan 返回的返回数组。 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).
由于此方法返回一个值(整数数组),因此您需要在调用方法 (main) 中的局部变量(int [] 类型)中“捕获”返回值。
For example: Assuming you pass the array “x” to the method and use array “y” to catch the returned value.例如:假设您将数组“x”传递给方法并使用数组“y”来捕获返回值。 Print x before you call the method and then print both x and y after calling the method.
在调用方法之前打印 x,然后在调用方法之后打印 x 和 y。
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.相反,您的“新”数组 (
y
) 指的是原始数组 ( a
),因此对y
任何更改实际上都是在原始数组中进行的。
I also recommend that you either test or try a
for null
ness.我还建议你要么测试或尝试
a
为null
湖。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.