QUESTION: I keep getting an error... the directions say ** Add a constructor to
ID: 638902 • Letter: Q
Question
QUESTION: I keep getting an error... the directions say **Add a constructor to your Bear class. Your constructor should take three (or four) parameters: an initial energy, its position (x and y location) and heading.***
public class BearClassDriver2 {
/** Creates a new instance of BearClassDriver2 */
public BearClassDriver2() {
}
public static void main(String[] args) {
Bear_pt2 myBear = new Bear_pt2 (myBear.energy, myBear.x, myBear.y, myBear.HeadingDirection);
while (myBear.energy > 0) {
myBear.step();
myBear.step();
myBear.step();
myBear.rotateRight();
myBear.step();
myBear.step();
myBear.step();
myBear.rotateRight();
myBear.step();
myBear.step();
myBear.step();
myBear.rotateRight();
myBear.step();
myBear.step();
myBear.step();
}
System.out.println("(" + myBear.x + ", " + myBear.y + ")");
}
}
Explanation / Answer
public class Bear_pt2
{
public int x;
public int y;
public int energy;
public char HeadingDirection;
public int s;
public void rotateRight()
{
System.out.println("right rotation");
}
public void step()
{
System.out.println(s);
s++;
}
Bear_pt2( int e, int a, int b , char hd)
{
energy=e;
x=a;
y=b;
HeadingDirection=hd;
}
public static void main(String[] args) {
Bear_pt2 myBear =new Bear_pt2(5,20,30,'r');
while (myBear.energy > 0) {
myBear.step();
myBear.step();
myBear.step();
myBear.rotateRight();
myBear.step();
myBear.step();
myBear.step();
myBear.rotateRight();
myBear.step();
myBear.step();
myBear.step();
myBear.rotateRight();
myBear.step();
myBear.step();
myBear.step();
myBear.energy=myBear.energy-1;
}
System.out.println("(" + myBear.x + ", " + myBear.y + ")");
}
}