简体   繁体   English

将两个1D数组转换为单个2D数组

[英]Convert two 1D arrays into single 2D array

I have 2 1d arrays and i am trying to populate them into a single 2d array in JAVA. 我有2个1d数组,我试图将它们填充到JAVA中的单个2d数组中。

For instance: 例如:

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

The results should then be: 结果应为:

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

This is my code 这是我的代码

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

This still produces wrong output 这仍然会产生错误的输出

i want to find Find all pairs with a given sum 我想找到查找给定总和的所有对

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];
}

should do the trick 应该可以

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM