Java question - can someone help?

Update:

I have a constructor where I am passing in a variable:

public Tree (int numberOfApples) - this variable was not previously declared in the class, we are passing it in, when I try this.numberOfApples=numberOfApples, I get an error message saying it can not resolve the variable

in a method, I want to use the variable

public numberLeft (int numberToRemove), and have it subtract the number to remove from the number of apples

Update 2:

here is my code:

public class Tree {

String fruitType;

int remainingApples;

Constructor:

public Tree(String fruitType, int numberOfApples) {

          

              this.fruitType = fruitType;  }

public boolean numberLeft(int numberToRemove) {

            remainingApples = numberOfApples - numberToRemove;

           if (remainingApples>=0) {

                      return true; }

           else return false;

}

how can I make this work?  I want to use the numberOfApples from the constructor

1 Answer

Relevance
  • EddieJ
    Lv 7
    4 weeks ago
    Favorite Answer

    this.numberOfApples=numberOfApples;

    is referring to 2 different variables.  The <this> resolves the problem, but it's not the only way to do it.

    You said, "variable was not previously declared in the class", but it NEEDS to be declared, so, just like you did with fruitType, you need to declare it.  The declaration inside the parameter list only declares the parameter -- NOT the required instance variable.

    remainingApples = numberOfApples - numberToRemove;

    if (remainingApples>=0) { return true; } 

    else return false;

    can be replaced with:

    remainingApples -= numberOfApples;

    return remainingApples >= 0;

    However, you might want to do something about a possibly negative remainingApples.

    • tiero4164 weeks agoReport

      Thank you very much for your time and assistance, I appreciate your help

    • Login to reply the answers
Still have questions? Get your answers by asking now.