0

I am working on my final project in my OOP1 class. The language is java.

I'd like to know how I invoke the following method inside my constructor:

public Garden (int size)    {

    garden=new char[size][size];

    this.initializeGarden(garden[][]);
}


private void intializeGarden(char [][]garden)   {

    for(int i=0;i<garden.length;i++)
        for(int j =0;j<garden.length;j++)
            garden[i][j]='-';

}

this.initializeGarden(garden[][]); is one of several failed attempts. I've tried a few variations, and eclipse didn't like any of them.

mtlchk
  • 11
  • 6
  • 3
    Just call `this.initializeGarden(garden)`, without the brackets. – Jai Nov 23 '18 at 03:27
  • 1
    Possible duplicate of [Can I call methods in constructor in Java?](https://stackoverflow.com/questions/5230565/can-i-call-methods-in-constructor-in-java) – Thiyagu Nov 23 '18 at 03:27
  • 1
    Have a look at [Why is it considered bad practice to call a method from within a constructor](https://stackoverflow.com/questions/18348797/why-is-it-considered-bad-practice-to-call-a-method-from-within-a-constructor) – Thiyagu Nov 23 '18 at 03:28
  • Is `initializeGarden` part of the class? Also, the [][] in that function call inside of the constructor is not needed. If you are getting any errors, could you edit your answer to include them? – Jonathan Van Dam Nov 23 '18 at 03:28

3 Answers3

2
public class Garden {
char[][] garden;

public Garden (int size)    {

    garden=new char[size][size];

    this.initializeGarden(garden);
}


private void initializeGarden(char [][]garden)   {

    for(int i=0;i<garden.length;i++)
        for(int j =0;j<garden.length;j++)
            garden[i][j]='-';

}

public void display(){
    for(int i=0;i<garden.length;i++){
        for(int j =0;j<garden.length;j++){
            System.out.print(garden[i][j]);
        }
        System.out.println();
    }


}


public static void main(String[] args) {
    new Garden(20).display();
}
}
0day
  • 103
  • 1
  • 10
0

Your private method intializeGarden appears to have a typo in it.

So the call would look like intializeGarden(garden)

TT--
  • 2,956
  • 1
  • 27
  • 46
  • Yes, I saw that after posting. Thanks :) Well, at least I was not totally out to lunch. "Hmm, this should work" Yeah it does, when you spell things right! – mtlchk Nov 23 '18 at 03:49
0

Simply change

this.initializeGarden(garden[][]);

to

this.initializeGarden(garden);

The above code will pass the garden variable as an argument to the initializeGarden method.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80