有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

将每2个元素组合成一个奇怪的数组,留下最后一个元素(Java)

下面是我尝试做的一个例子:

假设我有一个字符串数组,内容为{“a”、“b”、“c”、“d”、“e”} 和第二个数组,其内容为{“f”、“g”、“h”、“i”} 我想要在第一个数组上返回{“ab”、“cd”、“e”},在第二个数组上返回{“fg”、“hi”}的代码。我正在使用Java。下面是我写的不起作用的代码

    int val;
    if ((ciphertextVals.length % 2) == 0)
        val = ciphertextVals.length/2;
    else
        val = ciphertextVals.length/2 + 1;

    String[] encryptedBinary = new String[val];
    for (int i = 0; i <= ciphertextVals.length-1; i+=2)
    {
        String bin1 = Integer.toBinaryString(ciphertextVals[i]);
        String result;
        if (i == ciphertextVals.length-1)
        {
            result = bin1;
        }
        else
        {
            String bin2 = Integer.toBinaryString(ciphertextVals[i+1]);
            result = bin1 + bin2;
        }
        encryptedBinary[i/2+1] = result;
    }

共 (2) 个答案

  1. # 1 楼答案

    像这样的方法应该会奏效:

    public static void main(String[] args) {
    
        String[] input1 = { "a", "b", "c", "d", "e" };
        String[] input2 = { "f", "g", "h", "i" };
        String[] input3 = {};
    
        System.out.println(Arrays.toString(combine(input1))); //prints [ab, cd, e]
        System.out.println(Arrays.toString(combine(input2))); // prints [fg, hi]
        System.out.println(Arrays.toString(combine(input3))); // prints []
    }
    
    public static String[] combine(String[] input) {
        boolean isOdd = input.length % 2 != 0;
    
        int newLength = (input.length + 1) / 2;
        String[] output = new String[newLength];
    
        for (int i = 0; i < input.length / 2; i++) {
            output[i] = input[2 * i] + input[2 * i + 1];
        }
    
        if (isOdd) {
            output[output.length - 1] = input[input.length - 1];
        }
    
        return output;
    }
    
  2. # 2 楼答案

    实际上,您正在使逻辑变得复杂,这不是必需的
    你所说的可以写成这样的代码:

    ArrayList<String> encryptedBinaryList = new ArrayList<>();
    String temp = "";
    for (int i = 0; i < ciphertextVals.length; i++) {
        if (i % 2 == 0) {
            temp = Integer.toBinaryString(ciphertextVals[i]);
        } else {
        temp += Integer.toBinaryString(ciphertextVals[i]);
            encryptedBinaryList.add(temp);
        }
    }
    if (ciphertextVals.length % 2 != 0) {
        encryptedBinaryList.add(temp);
    }
    String encryptedBinary[] = new String[encryptedBinaryList.size()];
    encryptedBinaryList.toArray(encryptedBinary);
    

    要检查它是否工作,让我们用Integer.toString(ciphertextVals[i])替换Integer.toBinaryString(ciphertextVals[i]),并打印encryptedBinary的所有元素

    // when int ciphertextVals[] = {6,14,24,24,10,12,14};
    614
    2424
    1012
    14