Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects (Retired) Harnessing the Power of Objects Methods and Constants

Can't fix "cannot assign a value to final variable" in challenge

I just cannot fix this problem, it keeps saying that it cannot assign value to te mEnergyBars Object, what did I do wrong?

pls someone help me :(

GoKart.java
public class GoKart {
  private String mColor;
   public static final int MAX_ENERGY_BARS = 8;
  public static final int mEnergyBars;

  public GoKart(String color) {
    mColor = color;
    mEnergyBars = 0;
  }

  public void load () {
    mEnergyBars = MAX_ENERGY_BARS; 
  }

  public String getColor() {
    return mColor;
  } 
}

2 Answers

I would suggest starting over, and relating the challenge to the lesson material. This strategy may help throughout the course. Look at this code about the Pez Dispenser for your example to follow:

public class PezDispenser {
  public static final int MAX_PEZ = 12;
  private String mCharacterName;
  private int mPezCount;

  public PezDispenser(String characterName) {
    mCharacterName = characterName;
    mPezCount = 0;
  }

  public void load() {
    mPezCount = MAX_PEZ; 
  }

  public String getCharacterName() {
    return mCharacterName;
  }
}
  • Instead of MAX_PEZ, you are creating MAX_BARS
  • Instead of mPezCount, you are creating mBarsCount
  • Instead of a load method, you are creating a charge method
Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Krisztian;

You have the right idea, but I see a few issues with your code as it relates to this specific challenge. Let's start with Task 2.

Task 2

Now let's add a private uninitialized field to store the current number of energy bars. Name it mBarsCount. Initialize it to zero in the constructor.

1) I don't see a variable named mBarsCount in your code. 2) Your replacement variable, mEnergyBars was declared as final so you won't be able to alter or assign a value to it.

Task 3

Finally, let's add a method named charge. It should be public and return nothing. When called it should set mBarsCount to the value of the constant you declared in Task 1.

1) Again, I don't see a method with the name for which the challenge is looking.

Challenge engines here at Treehouse are looking for specific words, terms, syntax's, etc.

Post back if you are still stuck.

Happy coding,

Ken