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

标签 java

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/

相关文章:

java - 如何在oracle兼容模式和hibernate中使用hsqldb获取序列的下一个值

Java 8 并行流或方法执行

java - 在多个输出中播放音频

java - 如何最好地将递归函数转换为迭代函数?

java - 尝试运行我的程序时收到 NumberFormatException 错误

java - 从 Spring MVC XML 文件移动到 javaconfig。我真的迷失了我的数据库 XML 文件

java - 如何在 Ubuntu 上正确安装 Oracle Java 8?

java - 我的 Java 批处理作业在执行期间抛出异常。这算作 POSIX 失败吗?

java - 当不要求输入时,键入的文本显示在控制台中,我该如何阻止这种情况?

代码 :The state field path cannot be resolved to a valid type 中的 Java JPA Mysql 错误