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
        }

10-07 19:30
查看更多