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 Meet Objects Constructors

Razvan Cirstea
Razvan Cirstea
2,493 Points

Can we ask the user to input a name for the constructor ?


The use of the constructor is to create a customizable instance of the class, right ? So I was wondering how could we ask the user to input in the console a name for the constructor. For instance, if the customer wants his PEZ to be a "Darth Vader".

Can we implement such a method ? Does it make sense ? Here is the bit of code I have been writing in the class, but I am getting errors.

''' Console console = System.console(); private String name = console.readLine("Enter a name: ");

public PezDispenser( name ) { this.characterName=name; pezCount=0; } '''

1 Answer

The parameter in your constructor definition must have a type declared, so you need your constructor to look like this:

public PezDispenser(String name) {
  this.characterName = name;
  pezCount = 0;

You could do the following after you have created your pez dispenser class:

Console console =System.console();
String pez_name = console.readLine("Enter a name: ");

PezDispenser myPD = new PezDispenser(pez_name);

This would result in a new pez dispenser object with the name supplied by the user.

Razvan Cirstea
Razvan Cirstea
2,493 Points

Thank you very much for your answer, Ted. I understood the logic, however it seems I can't access the Console class anymore. That's strange, as in the Java Basics tutorial we were able to access it the same way.


Example.java:9: error: cannot find symbol
Console console =System.console();
symbol: class Console
location: class Example
1 error