gpt4 book ai didi

java - 我一直在研究这段代码,我调用了我的方法replaceLessThan(x,e),但我无法正确编写这个方法

转载 作者:行者123 更新时间:2023-12-01 11:46:37 25 4
gpt4 key购买 nike

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){

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();
}

}

我的其他方法工作正常,但我不知道如何操作 int[]x 数组来获取 12 来替换所有小于 12 的数字。我可以从 int[]x 获取小于 12 的数字进行打印但我无法用 12 来替换所有小于 12 的数字

最佳答案

修改您的 replaceLessThan 方法,如下所示,以替换所有小于 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; // Add this line to replace elements.
}
System.out.print (x[counter] + " "); // Move this statement out of if condition
}

关于java - 我一直在研究这段代码,我调用了我的方法replaceLessThan(x,e),但我无法正确编写这个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29091667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com