【问题标题】:Convert two 1D arrays into single 2D array将两个 1D 数组转换为单个 2D 数组
【发布时间】:2017-09-11 17:50:31
【问题描述】:

我有 2 个 1d 数组,我正在尝试将它们填充到 JAVA 中的单个 2d 数组中。

例如:

a[] = {2,7} 
b[] = {9,1} 

结果应该是:

result[][] = {{2,9}, {7,1}}

这是我的代码

    import java.util.Arrays;
    import java.util.Scanner;

    public class Main {

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter Test Cases:\t");
    int t = sc.nextInt();
    int[] a;
    int[] b;
    int i, j, x;
    for (int k = 0; k < t; k++) {
        System.out.println("Enter 1st Array Limit:\t");
        int len = sc.nextInt();

        System.out.println("Enter 2nd Array Limit:\t");
        int len1 = sc.nextInt();
        a = new int[len];
        b = new int[len1];
        System.out.println("Enter Sum Value");
        x = sc.nextInt();
        System.out.println("Enter " + len + " elements:\t");
        for (i = 0; i < len; i++) {
            a[i] = sc.nextInt();
        }
        System.out.println("Enter " + len1 + " elements:\t");
        for (j = 0; j < len1; j++) {
            b[j] = sc.nextInt();
        }
        int [][] c = new int[len][2];
        for (i = 0; i < len; i++) {
            for (j = 0; j < len1; j++) {
                if (a[i] + b[j] == x) {
                    for(int l = 0; i < a.length; i++){
                        c[l][0] = a[i];
                        c[l][1] = b[j];
                    }
                }
            }
        }
        System.out.println(Arrays.deepToString(c));
    }
}
}

这仍然会产生错误的输出

我想找到给定总和的所有对

【问题讨论】:

    标签: java arrays multidimensional-array


    【解决方案1】:
    int[] a = {2,7};
    int[] b = {9,1};
    int[][] c = new int[a.length][2];
    for(int i = 0; i < a.length; i++){
        c[i][0] = a[i];
        c[i][1] = b[i];
    }
    

    应该做的伎俩

    【讨论】:

    • 按照您的建议仍然没有得到正确的输出
    • 尝试复制并粘贴这段代码,然后运行它(告诉我它输出了什么): public static void main(String[] args) { int[] a = {2,7}; int[] b = {9,1}; int[][] c = new int[a.length][2]; for(int i = 0; i
    • [[2, 9], [7, 1]]
    • 这不是想要的输出吗?
    • 我试图让这个条件为真,然后将这两个元素插入数组 a[i]+b[j]==sum 然后插入 c[][];
    猜你喜欢
    • 2017-07-29
    • 2022-01-17
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 2017-11-02
    • 2021-05-27
    相关资源
    最近更新 更多