java - 如何将浮点条目的二维数组克隆到另一个类似类型和大小的二维数组?

标签 java arrays clone dimension

我在将浮点条目的二维数组克隆到另一个数组时遇到问题 类似类型和大小的二维数组。下面是我的代码,谁能帮我检查一下我哪部分错了?谢谢。

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

最佳答案

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

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

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

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!!!");
    }

关于java - 如何将浮点条目的二维数组克隆到另一个类似类型和大小的二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58182112/

相关文章:

java - 如何用 "EXCEPTION_ACCES_VIOLATION"解决 fatal error "Failed to write core dump."

c - 修改字符指针字符串数组(char * string[])

c - 将文件 .txt 读取到数组并拆分

java - 如何为具有多个可调用语句的执行器服务编写 Junit 测试用例

java - 为什么 Java 允许枚举常量的代码块?

c - 声明一个 long long 数组,大小为 unsigned int

java - Java 中的克隆对象

javascript - Vuex中如何深度克隆状态和回滚?

linux - 将 git 命令与 -q 一起使用,但在失败时不会保持安静?

java - 从 WLI 迁移到人工工作流程