public class ArrayExamples {
public static void main(String[] args) {
int c = 3;
int d =2;
System.out.println("c is " + c + " d is " + d);
swapInts(3,2);
int [] a = {1,2,3};
int [] b = {2,2,3};
int [] x = {3,45,17,2,-1,44,9,23,67,2,-6,-23,-100,12,5,1212};
int e = 12;
System.out.println();
for ( int z: a){
System.out.print( z + " ");
}
System.out.println();
for ( int y: b){
System.out.print( y + " ");
}
swapIntArrays (a,b);
System.out.println();
for ( int z: x){
System.out.print( z + " ");
}
replaceLessThan(x,e);
}
public static void replaceLessThan(int[] x, int e) {
System.out.println();
for (int counter = 0 ; counter<x.length; counter++){
if ( x[counter] < e){
x[counter] = e;
}
System.out.print (x[counter] + " ");
}
}
public static void swapInts(int c, int d){
int temp = c;
c=d;
d=temp;
System.out.println("c is " + c + " c is " + d);
}
public static void swapIntArrays (int []a, int []b){
System.out.println();
for(int i1=0; i1 < a.length; i1++){
int temp = a[i1];
a[i1] = b[i1];
b[i1]= temp;
System.out.print(a[i1] + " ");
}
System.out.println();
for(int i1=0; i1 < b.length; i1++){
System.out.print(b[i1] + " ");
}
System.out.println();
}
}
我想将数组x
传递给方法,并使用数组y
来捕获返回的值。我试图获得一个类似于replaceLessthan
的方法,该方法返回一个包含结果的数组,使原始数组保持不变。例如,在调用方法之前打印x
,然后在调用方法后打印x
和y
。
答案 0 :(得分:1)
public static int[] copyAndReplaceLessThan(int[] x, int e) {
System.out.println();
int[] results = new int[x.length];
for (int counter = 0 ; counter<x.length; counter++){
if ( x[counter] < e){
results[counter] = e;
} else {
results[counter] = x[counter];
}
}
System.out.println(Arrays.toString(x));
System.out.println(Arrays.toString(results));
return results;
}