java - 将两个数组合并为一个交替元素?

标签 java

我一直在尝试用以下算法解决这个问题,但它不起作用。

import java.util.Scanner;
import java.lang.Math;

public class AlterConcatenateArrays {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        System.out.println("How many elements do you want the first array have?");
        int N = s.nextInt();
        s.nextLine();
        System.out.println("How many elements do you want the second array have?");
        int M = s.nextInt();
        int[] a = new int[N];
        int[] b = new int[M];
        System.out.println("The elements of the first array are: ");
        for (int i = 0; i < N; i++) {
            a[i] = (int) (Math.random() * 20);
            System.out.print(a[i] + " \n");
        }
        System.out.println("The elements of the second array are: ");
        for (int i = 0; i < M; i++) {
            b[i] = (int) (Math.random() * 20);
            System.out.print(b[i] + " \n");
        }
        System.out.println("Now we are going to concatenate the arrays by alternatingly choosing");
        int[] c = new int[N + M];
        for (int i = 0; i < ((N + M) / 2); i++) {
            a[i] = c[2 * i + 0];
            b[i] = c[2 * i + 1];
        }
        System.out.println("The new array is: ");
        for (int i = 0; i < N + M; i++) {
            System.out.print(c[i] + "\t");
        }
    }
}

该程序的输出是这样的:

How many elements do you want the first array have?
2
How many elements do you want the second array have?
3
The elements of the first array are: 
17 
18 
The elements of the second array are: 
6 
14 
15 
Now we are going to concatenate the arrays by alternatingly choosing
The new array is: 
0   0   0   0   0   

最佳答案

您已在此处交换了作业。

{
    a[i] = c[2*i+0];
    b[i] = c[2*i+1];
}

应该从ab分配到c,就像

{
    c[2*i+0] = a[i];
    c[2*i+1] = b[i];
}

关于java - 将两个数组合并为一个交替元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35256734/

相关文章:

java - 从java获取存储过程OUT参数名称

java - 从 Android 异步嵌套类返回值

java - Swagger 启动 tomcat 时抛出 UncheckedExecutionException

java - 发送邮件到 Gmail 帐户

java - 实现客户端多文件上传服务的有效方法

java - 更改变量但保留它保存?

java - 默认实现还是抽象方法?

java - JPA 持久性属性干扰 JAXB

java - 序列化(或解析)Protobuf 对象

java - 循环,编程新手