簡體   English   中英

來自兩個不同數組的JAVA數組串聯

[英]JAVA array concatenation from two different arrays

如何連接2個數組中的每個數字,然后分別給出新編號的輸出。 形成了?

例:

arr1[1,2,3] 
arr2[2,3,5] 
output: [12,13,15,22,23,25,32,33,33,35]

這是另一種不使用String

public static void main(String[] args)
{
    int[] arr1 = { 1, 2, 3 };
    int[] arr2 = { 2, 3, 5 };
    int[] arr = concat(arr1, arr2);     
    System.out.println(Arrays.toString(arr));
}

static int[] concat(int[] arr1, int[] arr2)
{
    int i = 0;
    int[] arr = new int[arr1.length * arr2.length];
    for (int n2 : arr2)
    {
        int pow10 = (int) Math.pow(10, nDigits(n2));
        for (int n1 : arr1)
        {
            arr[i++] = n1 * pow10 + n2;
        }
    }
    return arr;
}

static int nDigits(int n)
{
    return (n == 0) ? 1 : 1 + (int) Math.log10(n);
}

輸出:

[12, 22, 32, 13, 23, 33, 15, 25, 35]

for循環內使用for循環。 然后將arr的項目和arr2的項目連接起來。 我使用了ArrayList但是如果您知道數組的結果長度,則可以使用普通數組。

    String[] arr = new String[]{"1", "2", "3"};
    String[] arr2 = new String[]{"2", "3", "5"};
    List<String> res = new ArrayList<>();

    for (int i = 0; i < arr.length; i++){
        for (int j = 0; j < arr2.length; j++) {
            res.add(arr[i] + arr2[j]);
        }
    }

    System.out.println(res.toString());

結果是:

[12, 13, 15, 22, 23, 25, 32, 33, 35]

如果您只想以上面給出的形式顯示兩個數組的內容,則可以始終嘗試執行此操作,而不是對其進行概括。

public class ArrayQuestion {
public static void main(String[] args) {
    int arr1[] = {1,2,3};
    int arr2[] = {2,3,5};
    for(int i=0;i<arr1.length;i++) {
        for(int j=0;j<arr2.length;j++) {
            System.out.print(arr1[i]);
            System.out.print(arr2[j]);
            System.out.println();
        }
    }

}

}

輸出: 12 13 15 22 23 25 32 33 35

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM