No idea what to do for this
Here is the prompt I got-
The code below shows some of the text for a class called City. As you can see, a City has two instance variables, name and population. Write a complete public constructor (including header line) with no parameters, which sets the population to an initial value of -1, and the name to an initial value of "unknown".
Code :
public class City {
private String name;
private int population;
thats all i know haha
Re: No idea what to do for this
I believe what you're being asked to do is something like this:
Code :
public City(String _name, int _population)
{
population = _population;
name = _name;
}
And then create a "City":
Code :
City NewCity = new City("New York", 100);
See how I use the constructors I created in making a new "City"?
I'm a beginner but I'm pretty sure that's right.
Re: No idea what to do for this
Then what is the actual answer? because all i have so far is
Code :
public class City {
private String name;
private int population;
so im not sure what follows it
Re: No idea what to do for this
It would be:
Code :
public class City {
public static void main(String args[]){
private String name;
private int population;
public City(String _name, int _population)
{
population = _population;
name = _name;
}
City NewCity = new City("New York", 100);
}
}
Re: No idea what to do for this
Yeah, that didn't work.
I tried substituting "unknown" for "New York" and -1 for 100 because thats what the prompt said but that didnt work either
Re: No idea what to do for this
I figured it out.
Code :
public City()
{
name = "unknown";
population = -1;
}
is what has to be put in
Re: No idea what to do for this
Uhmmmm, that's not a constructor method but sure that will work, I didn't realize you wanted it that simple lol.
Re: No idea what to do for this
That is a constructor. It's what's known as a "default constructor", i.e. it intializes all the values to some pre-determined initial value, in this case -1 and "unknown".
As a second note, if you are going to be providing other constructors that create an initial value (say, a constructor which also sets the city name), I would recommend calling that constructor from the the default constructor. This reduces the amount of code you have to check for problems.
Code Java:
public City()
{
// call the other constructor that actually assigns values
this("unknown", -1);
}
public City(String name, int population)
{
this.name = name;
this.population = population;
}