【问题标题】:How to clone a two-dimensional array of float entries to another two-dimensional array of similar type and size? [duplicate]如何将浮点条目的二维数组克隆到另一个类似类型和大小的二维数组? [复制]
【发布时间】:2020-01-30 14:06:19
【问题描述】:

我有一个问题,将浮点条目的二维数组克隆到另一个数组 相似类型和大小的二维数组。以下是我的编码,任何人都可以帮助我检查我错了哪一部分?谢谢。

public class Clone2Darray {
    public static int[][] clone(int[][] a) throws Exception {
        float b[][] = new int[a.length][a[0].length];

        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[0].length; j++)
                b[i][j] = a[i][j];
        }
        return b;
    }

    public static void main(String args[]) {

        float a[][]= {{1.513,2.321,3.421},{4.213,5.432,6.123},{7.214,8.213,9.213}};


        try {
            float b[][] = Clone2Darray.clone(a);
            for (int i = 0; i < a.length; i++) {
                for (int j = 0; j < a[0].length; j++) {
                    System.out.print(b[i][j] + " ");
                }
                System.out.println();
            }
        } catch (Exception e) {
            System.out.println("Error!!!");
        }
    }
}

我的编码出现如下错误:

  C:\Users\User-Win7\.netbeans\7.1\var\cache\executor-snippets\run.xml:48: 
  Cancelled by user.
  BUILD FAILED (total time: 4 seconds)

我想要如下输出:

  1.513 2.321 3.421
  4.213 5.432 6.123
  7.214 8.213 9.213

  1.513 2.321 3.421
  4.213 5.432 6.123
  7.214 8.213 9.213

【问题讨论】:

  • 那么你的问题是什么,你能说出你有什么结果,有什么问题吗?
  • 您在clone 方法中到处使用int 数组,如果您想保留类型,这些数组必须是float 数组。当前代码不会以这种方式编译。
  • 如果你想克隆一个浮点数组,为什么在你的克隆方法中使用int[][]

标签: java arrays clone dimension


【解决方案1】:

1 - 将方法参数从 int 更改为 float。

2 - 将返回类型从 int 更改为 float。

3 - 在数组中分配浮点值时,在每个数字之后使用 f 来告诉编译器它是一个浮点数。

public static float[][] clone(float[][] a) throws Exception {
    float b[][] = new float[a.length][a[0].length];

    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[0].length; j++) {
            b[i][j] = a[i][j];
        }
    }
    return b;
}



    float[][] a = new float[][] { { 1.513f, 2.321f, 3.421f }, { 4.213f, 5.432f, 6.123f },
            { 7.214f, 8.213f, 9.213f } };

    try {
        float b[][] = clone(a);
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[0].length; j++) {
                System.out.print(b[i][j] + " ");
            }
            System.out.println();
        }
    } catch (Exception e) {
        System.out.println("Error!!!");
    }

【讨论】:

  • 是的。输出可以显示浮点数。但是不能出现克隆数组。
  • 但无法出现克隆数组——什么意思?
  • 意思是要复制相同的数组
  • 它将复制相同的数组。 f 表示法用于编译器。它不会改变或影响任何事情。
猜你喜欢
  • 2021-12-31
  • 2013-10-31
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
相关资源
最近更新 更多