从另一个数组创建一个数组?

时间:2020-03-07 21:53:33

标签: java arrays encoding

java的新手,并且正在使用RLE编码,我正在尝试创建一个程序,该程序采用一个字节数组,然后返回另一个字节数组,但是它采用数组中连续值的数量,然后打印[(重复),((值)]。例如,[13,13,13,3,3,3,3]将返回[3,13,4,3]

import java.util.Arrays;

public class testing {

    public static void main(String [] args) {

        byte [] pracArray = {13,13,13,3,3,3,3};

        int count = 1;

        for (int i = 0; i <pracArray.length-1; i++)
        {
            if (pracArray[i] != pracArray[i+1])
            {
                count++;
            }
        }

        byte numLength = 1;
        byte indexNum = 0;
        int newArraySize = count*2;

        byte [] newArray = new byte [newArraySize];

        for ( int i = 0; i < pracArray.length-1; i++)
        {
            if (pracArray[i] != pracArray[i+1] )
            {
                newArray[indexNum] = numLength;
                newArray[indexNum+1] = pracArray[i];
                indexNum = (byte) (indexNum + 2);
                numLength = 1;
            }
            else
            {
                numLength++;
            }
        }
        System.out.println(Arrays.toString((pracArray)));
        System.out.println(Arrays.toString((newArray)));
    }
}

我知道我的问题,最近一次运行的连续数字未打印出来。如果我将数组更改为[13,13,13,3,3,3,3,1],它将打印[3,13,4,3,0,0],最后的数字序列将永远不会记录,因此newArray的最后两个值永远不会被填充。关于如何更改if语句以包括我的最后一个数字序列的任何想法?

1 个答案:

答案 0 :(得分:1)

在循环终止时,检查最后一个元素是否等于倒数第二个元素。

您更新后的代码将是:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {

        byte[] pracArray = { 13, 13, 13, 3, 3, 3, 3, 1 };

        int count = 1;

        for (int i = 0; i < pracArray.length - 1; i++) {
            if (pracArray[i] != pracArray[i + 1]) {
                count++;
            }
        }

        byte numLength = 1;
        byte indexNum = 0;
        int newArraySize = count * 2;

        byte[] newArray = new byte[newArraySize];
        int i;
        for (i = 0; i < pracArray.length - 1; i++) {
            if (pracArray[i] != pracArray[i + 1]) {
                newArray[indexNum] = numLength;
                newArray[indexNum + 1] = pracArray[i];
                indexNum = (byte) (indexNum + 2);
                numLength = 1;
            } else {
                numLength++;
            }
        }
        if (pracArray[i - 1] == pracArray[i]) {
            newArray[indexNum] = numLength;
            newArray[indexNum + 1] = pracArray[i];
            indexNum = (byte) (indexNum + 2);
            numLength = 1;
        } else {
            newArray[indexNum] = numLength;
            newArray[indexNum + 1] = pracArray[i];
        }

        System.out.println(Arrays.toString((pracArray)));
        System.out.println(Arrays.toString((newArray)));
    }
}

输出:

[13, 13, 13, 3, 3, 3, 3, 1]
[3, 13, 4, 3, 1, 1]

byte[] pracArray = { 13, 13, 13, 3, 3, 3, 3 }的输出如下:

[13, 13, 13, 3, 3, 3, 3]
[3, 13, 4, 3]