Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

Sam Asghar
Sam Asghar
800 Points

Hi Guys! Please explain:

I was trying to make a similar program to PezDispenser.java but instead of declaring the name in the program i wanted the user to have that option. So i imported the Scaner for this task. What am in doing wrong?


import java.util.Scanner;

public class Test2 {

public static void main(String[] args) {

Scanner bubbleName = new Scanner(System.in);

System.out.println ("Hi! What Bubble Head do you want?");

String bubbleAnswer = bubbleName.nextLine();

BubbleHead bubbleHead = new BubbleHead(bubbleAnswer);

System.out.println("Your Bubble Head is" + bubbleHead.getBubbleName());

}

}


class BubbleHead {

final private String mBubbleName;

public BubbleHead(String headName) {

headName = this.bubbleName;

}

public String getBubbleName() {

return headName;

}

}


./BubbleHead.java:13: error: cannot find symbol return headName; ^ symbol: variable headName location: class BubbleHead 1 error

1 Answer

andren
andren
28,520 Points

There are a couple of issues in the BubbleHead class.

  1. In the constructor you set headName which is the parameter that is passed in to a field variable called bubbleName. This is wrong both in the sense that it is the opposite of what you want to do (you want to set the field variable equal to the parameter) and in the sense that bubbleName is not the right name for the field variable. In your class you have called the name field variable mBubbleName.

  2. In the getBubbleName you return a variable which does not exist, I assume you intended to return mBubbleName.

If you fix the order and naming of the variables in the contructor and fix the name of the variable used in the getter method like this:

class BubbleHead {

    final private String mBubbleName;

    public BubbleHead(String headName) {
        mBubbleName = headName;
    }

    public String getBubbleName() {
        return mBubbleName;
    }

}

Then your code should work. Note that I also removed the "this" keyword, that is only needed when the field variable and parameter share the same name.

Sam Asghar
Sam Asghar
800 Points

Thank you! You are the best!