Bfrank
Bfrank

Reputation: 33

having trouble with double arrays

I'm having a little issue with my program. Basically, I want to use a double array to set all even elements to 0 and all odd elements to 1. My output should be:

001 001 11

Instead, my output is:

000 111 000

Any suggestions on how to fix this?

public class SetOf0and1 {

    public static void main(String[]args)
    {

        int [][] numbers1 = {{4,2,5}, {2,4,1}, {1,3}};

        System.out.println("Before setting elements between 0 and 1: ");
        displayArray(numbers1);

        setEvenRowsTo0OddRowsTo1 (numbers1);
        System.out.println("After setting the elements between 0 and 1");
        displayArray(numbers1);

    }

    public static void setEvenRowsTo0OddRowsTo1(int [][]array)
    {
    for(int i=0; i<array.length;i++)
    {
        for(int j=0; j<array[i].length;j++)
        {
            if(i%2 == 0)
            array[i][j]=0;
            else
                array[i][j]=1;

    }
    }
}
    public static void displayArray(int [][]array)
    {
        for(int i=0;i<array.length;i++)
        {
            for( int j=0; j<array[i].length;j++)            {
                System.out.print(array[i][j] + " " );
            }
            System.out.println();

    }

    }

}

Upvotes: 0

Views: 44

Answers (2)

enrico.bacis
enrico.bacis

Reputation: 31524

You are checking whether the index i is odd or even instead of the element. The line:

if(i%2 == 0)

should be:

if(array[i][j]%2 == 0)

Upvotes: 2

Dici
Dici

Reputation: 25980

Your test is wrong :

if(i%2 == 0)

should be

if(array[i][j] % 2 == 0)

Upvotes: 4

Related Questions