如何确定数组索引是否均匀?

时间:2016-11-29 19:08:09

标签: java arrays if-statement multidimensional-array

我正在进行一项任务,我必须逐行填充二维数组。如果行的索引值为偶数(0,2,4等等),则该行必须从从右到左填充。如果行的索引值不均匀(1,3,5等等),则必须从从左到右填充。我应该在if语句中添加什么条件才能以这种方式填充行?

谢谢!

3 个答案:

答案 0 :(得分:2)

您需要使用模数或余数运算。假设 i 是一个不均匀的数字,因此 i%2 将评估为 1 。对于偶数, i%2 将导致 0 。正如评论中指出的那样,使用条件 if (row_index % 2 == 0) {*do right to left thing*} else {do right to left thing}

答案 1 :(得分:2)

作为具有奇怪名称的用户,我不知道如何引用(抱歉,随意在这里编辑你的名字)指出,i%2 == 0应该解决问题。

%(modulo)运算符返回整数除法的余数,因此如果行数是偶数,则可以将其除以2且没有余数(i%2 == 0)

int[][] toBeFilled = new int[width][height];
for(int i=0;i<width;i++) {
    if(i%2==0)
        //Fill toBeFilled[i] from Right to Left
    else
        //Fill toBeFilled[i] from from Left to Right
}

答案 2 :(得分:0)

这是一个可能有用的代码示例。请注意,这是C#(我现在不是坐在Java编译器前面)所以有一些非常小的语法差异,但它应该仍然非常易读。

    private static int[][] BuildArrays()
    {
        Random random = new Random();

        // Whatever size you want
        int[][] array = new int[random.Next(1, 100)][];

        for (int i = 0; i < array.Length; i++)
        {
            // Make an array of whatever size you want
            array[i] = new int[random.Next(1, 50)];

            // % is the modulo operator
            // Basically, this means "remainder when the index is divided by 2"
            // By definition, even numbers are evenly divisible by 2 and odd numbers aren't
            if (i % 2 == 0)
            {
                // Even - we fill right to left
                for (int j = array[i].Length - 1; j >= 0; j--)
                {
                    // Enter whatever you want
                    array[i][j] = random.Next();
                }
            }
            else
            {
                // Odd - we fill left to right
                for (int j = 0; j < array[i].Length; j++)
                {
                    array[i][j] = random.Next();
                }
            }
        }

        return array;
    }
相关问题