Search code examples
javaconstructorparameterized

Issue with creating an object from a parameterized constructor with an array as a parameter


I'm working on a Java project for a Yahtzee game and need to create a parametrized constructor that gives both of my instance variables their values. My two instance variables are arrays.

    public DiceArray(int[] die)
{
    die = new int[5];
    for( int i = 0; i < die.length; i++ )
    {
        die[i] = 0;
    }

    keep = new boolean[5];
    for( int i = 0; i < keep.length; i++ )
    {
        keep[i] = false;
    }       
}

When I try to create the object in my application class with

    // Testing parameterized constructor
    DiceArray myDice = new DiceArray();

I get Exception in thread "main" java.lang.Error: Unresolved compilation problem: The constructor DiceArray() is undefined

When I take the parameter out of the method it works fine. Thanks in advance for any help


Solution

  • You have not defined default constructor and you are trying to call default constructor, which is why compiler is not happy.

    You need to use parameterized constructor in your case like:

    int num[] = new int[5];
    DiceArray myDice = new DiceArray(num);
    

    And remove the num array initialization from your method as it's not advisable to modify the parameter's that you get in the method/constructor as it wont have any effect (i.e. it wont change anything in your array num that you defined just before calling constructor as above) on the calling method like we defined above.

    In fact, i don't see you should be using constructor at all. (Assuming you have declared num and result array at object level already)As by default when you create int array, all the values are going to be 0 by default and for result i.e. boolean array, they will default to false.

    So just remove the constructor and its body and it should work.