Matt.C Matt.C - 20 days ago 5
Java Question

How to call a method to a constructor?

I'm trying to call the setDirection() method to the bottom of my constructor. I thought I could do it by simply writing the methods name at the bottom but whenever I construct the object it doesn't do anything. The xDirection and yDirection values are still 0 when it should be set to a random number between 0-19.

It's either that or my method is wrong.

public class Bubble
{
// instance variables - replace the example below with your own
private Circle bubble;
private int xDirection;
private int yDirection;
private Random generator;

public Bubble()
{
// initialise instance variables
bubble = new Circle();
bubble.randomizePosition();
generator = new Random();
setDirection();
}

/**
*/
public void setDirection()
{
// put your code here
int xDirection = generator.nextInt(20);
int yDirection = generator.nextInt(20);
boolean bool = generator.nextBoolean();

if(bool == true){
xDirection = (xDirection * 1);
yDirection = (yDirection * 1);
}
}


}

Answer

You are declaring a local variables in the method. These shadow the class fields.

public void setDirection()
{
    int xDirection = generator.nextInt(20); //   You are declaring a local xDirection here
    int yDirection = generator.nextInt(20);
    boolean bool = generator.nextBoolean();

    if(bool == true){
        xDirection = (xDirection * 1);
        yDirection = (yDirection * 1);
    }
}

Instead,

public void setDirection()
{
    xDirection = generator.nextInt(20); //   Dont use int here
    yDirection = generator.nextInt(20);
    boolean bool = generator.nextBoolean();

    if(bool == true){
        xDirection = (xDirection * 1);
        yDirection = (yDirection * 1);
    }
}
Comments