Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

if-else-else if statements in Java (codecademy)

I’m just starting to learn Java and I just got to the if-else-else if statements section on CodeAcademy. I tried using the if else statement in a method, but I’m not receiving the variable value when I call it, only the if-else statement. I’m guessing this is a very small mistake.

(This is my first post so if I’m using any of the features incorrectly, let me know)

Thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Dog{
  String name;
  double weight;
  int age;

  public Dog(String dogName, double dogWeight, int dogAge){
    String name = dogName;
    double weight = dogWeight;
    int age = dogAge;

    if (dogAge == 10){
      System.out.println("He's getting a bit older!");
    } else if (dogAge < 10) {
      System.out.println("He is still young!");
    } else if (dogAge > 10){
      System.out.println("Make sure he is healthy!");
    }

  }

  public static void main(String[] args){
    Dog coco = new Dog("CoCo", 15.67, 11);
    System.out.println(coco.age);



  }
}

The output I get from this is:

Make sure he is healthy!
0

>Solution :

In your constructor, you’re declaring new variables local to the method that happen to have the same name as your object’s properties.

  public Dog(String dogName, double dogWeight, int dogAge){
    String name = dogName;
    double weight = dogWeight;
    int age = dogAge;

To overwrite your object’s properties, you can remove the type declaration in order to refer to an existing variable.

  public Dog(String dogName, double dogWeight, int dogAge){
    name = dogName;
    weight = dogWeight;
    age = dogAge;

You can also utilize the this object, which disambiguates between the object’s properties and similarly named variables. It helps with readability as well.

  public Dog(String dogName, double dogWeight, int dogAge){
    this.name = dogName;
    this.weight = dogWeight;
    this.age = dogAge;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading