Reputation: 1431
I am learning Java using Codecademy. I am trying to write code that would make an object (in this case a 3 year old dog named Spike) to run on on n
legs where n = age
. I tried "brute force debugging", but that didn't work. How should I change the line "how to change this" to make the code work?
class Dog {
public Dog(int dogsAge) {
int age = dogsAge;
}
public void bark() {
System.out.println("Woof!");
}
public void run(int feet) {
System.out.println("Your dog ran " + feet + " feet!");
}
public static void main(String[] args) {
Dog spike = new Dog(3);
spike.bark();
spike.run(this.age); // How to change this?
}
}
Upvotes: 0
Views: 258
Reputation: 6876
class Dog {
int age; //your mistake
public Dog(int dogsAge){
this.age = dogsAge;
}
public void bark() {
System.out.println("Woof!");
}
public void run(int feet) {
System.out.println("Your dog ran " + feet + " feet!");
}
public static void main(String[] args) {
Dog spike = new Dog(3);
spike.bark();
spike.run(spike.age); // How to change this?
}
Upvotes: 2
Reputation: 352
Your class needs to - add storage for the age variable - set that value in the construcor - provide a way for your main function to access it
class Dog {
private int age; //storage for the age value within the instance
public Dog(int dogsAge){
this.age = dogsAge; // set the value
}
// provide a way to access the age
public int getAge() {
return this.age;
}
public void bark(){
System.out.println("Woof!");
}
public void run(int feet) {
System.out.println("Your dog ran " + feet + " feet!");
}
public static void main(String[] args) {
Dog spike = new Dog(3);
spike.bark();
spike.run(spike.getAge()); // retrieve the age and use it
}
}
Upvotes: 3
Reputation: 8387
Try to create a variable int age
and initialize it in constructor like this:
class Dog {
int age;
public Dog(int dogsAge){
this.age = dogsAge;
}
Upvotes: 2