So I'm having an issue when I create Variable Arguments with multiple classes. As you can see on the code below, I'm just trying to take in multiple cities and districts in a random order and try to print out the population of the entire state. Except the issue is I have no idea how to iterate through my CAndD array in order to add all of the populations together.
Code:
public class Main {
public static void main(String args[]) {
State S = new State("Florida", new District("Miami-Dade", 2752000),
new City("Miami", 463347),
new City("Tampa", 385430),
new District("Broward", 1936000));
System.out.println("The Population is: " + S.getPopulation());
}
}
class CitiesAndDistricts {
}
class City extends CitiesAndDistricts{
String name;
int population;
public City(String name, int population) {
this.name = name;
this.population = population;
}
}
class District extends CitiesAndDistricts{
String name;
int population;
public District(String name, int population) {
this.name = name;
this.population = population;
}
}
class State {
String name;
int population;
CitiesAndDistricts[] CAndD;
public State(String name, CitiesAndDistricts ... entities) {
this.name = name;
CAndD = entities;
for(int i = 0; i < CAndD.length; i++) {
this.population += CAndD[i].population;
}
}
public int getPopulation() {
return population;
}
}
If anyone can help me solve this problem that'd be great!
Please Have a look at below code, I have moved population variable from City and District to parent class:
public class Main {
public static void main(String args[]) {
State S = new State("Florida", new District("Miami-Dade", 2752000),
new City("Miami", 463347),
new City("Tampa", 385430),
new District("Broward", 1936000));
System.out.println("The Population is: " + S.getPopulation());
}
}
class CitiesAndDistricts {
int population;
}
class City extends CitiesAndDistricts{
String name;
public City(String name, int population) {
this.name = name;
this.population = population;
}
}
class District extends CitiesAndDistricts{
String name;
public District(String name, int population) {
this.name = name;
this.population = population;
}
}
class State {
String name;
int population;
CitiesAndDistricts[] CAndD;
public State(String name, CitiesAndDistricts ... entities) {
this.name = name;
CAndD = entities;
for(int i = 0; i < CAndD.length; i++) {
this.population += CAndD[i].population;
}
}
public int getPopulation() {
return population;
}
}
Designing an empty parent class seems not good. In your code, the class City and District are the same. I assume that you want to know the type of place (City or District). The better solution is moving all the properties of the child class to the parent class. The class CitiesAndDistricts would be:
class CitiesAndDistricts {
String name;
int population;
public CitiesAndDistricts(String name, int population} {
this.name = name;
this.population = population;
}
}
From this parent class, you can extend to class City and District as below:
class City extends CitiesAndDistricts{
public City(String name, int population) {
super(name, population);
}
}
class District extends CitiesAndDistricts{
public District(String name, int population) {
super(name, population);
}
}
Related
So I'm supposed to use a "Summable" interface to add up the populations of the cities. I've been staring at it for an hour but still can't find my error. Please Help!
This is my tester
public class SummableTester extends ConsoleProgram
{
public void run()
{
City cookie = new City("Coookie", 20000);
City taco = new City("Taco", 10000);
System.out.println(taco.getValue());
}
}
City Class:
public class City
{
private String name;
private int population;
public City(String name, int population)
{
this.name = name;
this.population = population;
}
public String getName()
{
return this.name;
}
public int getValue()
{
return this.population;
}
public int add(Summable other)
{
return getValue() + other.getValue();
}
}
Summable:
public interface Summable
{
public int add(Summable other);
public int getValue();
}
You implemented Summable interface in your City class, but forgot to include implements Summable in city class.
public class City implements Summable {
}
I'm having issues with this code running, I'm trying to get the program to print the strings below by using input from the other classes. As you can see, the info put into the new Bride and Location objects are being put in to a Wedding Object and then I need to try and retrieve the details from the wedding object and display it on screen like so:
Wedding data:
Bride: Amy Cronos, age: 29
Location: South Rd, suburb: Tonsley
but I am instead met with 4 identical errors relating to the place.getName, place.getSuburb() etc. etc. that say
Main.java:6: error: cannot find symbol
System.out.println("Location"+place.getStreet()+", suburb:
"+place.getsuburb());
symbol: variable place
location: class Main
I'm pretty sure this has something to do with the scope, but cant work out what I need to do.
What is causing this error and how do I fix it?
Here is the code:
public class WeddingDetails {
public static void main(String[] args) {
Bride person = new Bride("Amy Cronos", 29);
Location place = new Location("Tonsley", "South Rd");
Wedding wed = new Wedding(person, place);
show(wed);
}
public static void show(Wedding wed) {
System.out.println("Wedding data:");
System.out.println("Bride: " + person.getName() + ", age: " + person.getAge());
System.out.println("Location: " + place.getStreet() + ", suburb: " + place.getSuburb());
}
public static class Location {
private String suburb;
private String street;
Location(String suburb, String street) {
this.suburb = suburb;
this.street = street;
}
public String getSuburb() {
return suburb;
}
public String getStreet() {
return street;
}
}
public static class Bride {
private String name;
private int age;
Bride(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public static class Wedding {
private Bride person;
private Location place;
Wedding(Bride person, Location place) {
this.person = person;
this.place = place;
}
public Bride getBride() {
return person;
}
public Location getPlace() {
return place;
}
}
}
The issue here is your println statements are trying to access methods within objects, but by calling those methods on the wrong object. You should be accessing the Bride and Location objects with the Wedding class' getters (getBride() and getPlace(). The complete call would be wed.getBride().getName() and wed.getPlace().getStreet() so on.
Corrected code is below. NOTE: for the purposes of being able to compile all of the code inside one class, I added the static keyword to the Bride, Location and Wedding class declarations. You can just remove the static and copy and paste each class back into your .java files.
public class WeddingDetails {
public static void main(String[] args) {
Bride person = new Bride("Amy Cronos", 29);
Location place = new Location("Tonsley", "South Rd");
Wedding wed = new Wedding(person, place);
show(wed);
}
public static void show(Wedding wed) {
System.out.println("Wedding data:");
System.out.println("Bride: " + wed.getBride().getName() + ", age: " + wed.getBride().getAge());
System.out.println("Location: " + wed.getPlace().getStreet() + ", suburb: " + wed.getPlace().getSuburb());
}
public static class Location {
private String suburb;
private String street;
Location(String suburb, String street) {
this.suburb = suburb;
this.street = street;
}
public String getSuburb() {
return suburb;
}
public String getStreet() {
return street;
}
}
public static class Bride {
private String name;
private int age;
Bride(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public static class Wedding {
private Bride person;
private Location place;
Wedding(Bride person, Location place) {
this.person = person;
this.place = place;
}
public Bride getBride() {
return person;
}
public Location getPlace() {
return place;
}
}
}
Hi I have created a toStringmethod in one of my classes which can be seen below.
Student Class:
package Practical5;
public class Student extends Person {
//instance variables
private static int MAX_MODULES = 6;
private StudentMode modeOfStudy;
private boolean studentLoan;
private int numEnrolledModules;
//constructor
public Student(String name, String dob, Address address, StudentMode modeOfStudy, boolean studentLoan) {
super(name, dob, address);
this.modeOfStudy = modeOfStudy;
this.studentLoan = studentLoan;
this.numEnrolledModules = 0;
}
//accessors & mutators
public StudentMode getMode() {
return modeOfStudy;
}
public boolean isStudentLoan() {
return studentLoan;
}
public int getNumEnrolledModules() {
return numEnrolledModules;
}
public void setMode(StudentMode modeOfStudy) {
this.modeOfStudy = modeOfStudy;
}
public void setStudentLoan(boolean studentLoan) {
this.studentLoan = studentLoan;
}
public void setNumEnrolledModules(int numEnrolledModules) {
this.numEnrolledModules = numEnrolledModules;
}
#Override
public void purchaseParkingPass() {
System.out.println(getName() + " just purchased a parking pass with student discount.");
}
#Override
public void addModule(String moduleCode) {
if (getNumEnrolledModules() < MAX_MODULES) {
System.out.println(getName() + " successfully registered for the module: " + moduleCode);
}
else {
System.out.println("You are unable to register for " + moduleCode + " as the maximum number of permitted module enrolments has been reached.");
}
}
public String toString() {
return "Student [ ID: " + getId() + "; Name: " + getName() +
"; DOB: " + getDob() + "; Study Mode: " + getMode() +
"; Number of Enrolled Modules: " + getNumEnrolledModules();
}
}
Person Class:
package Practical5;
public abstract class Person {
//instance variables
private static int LAST_ID = 1000 + 1;
private int id;
private String name;
private String dob;
private Address address;
//constructor
public Person(String name, String dob, Address address) {
super();
LAST_ID ++;
this.id = LAST_ID;
}
//accessors & mutators
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getDob() {
return dob;
}
public Address getAddress() {
return address;
}
public void setName(String name) {
this.name = name;
}
public void setDob(String dob) {
this.dob = dob;
}
public void setAddress(Address address) {
this.address = address;
}
//methods
public abstract void purchaseParkingPass();
public abstract void addModule(String moduleCode);
}
I then created a tester class and created a new ArrayList and added these elements to it.
I then created a for loop in order to loop through each element and call the toString method to print out the details of each element but it is returning null values.
Tester Class:
package Practical5;
import java.util.ArrayList;
import java.util.Scanner;
public class UIS_Tester {
public static void main(String[] args) {
Student student1 = new Student("James Black", "07/09/1995" , new Address("Wheeler's Road",10,"Belfast", "BT12 5EG", "Co.Antrim"),StudentMode.Fulltime, false);
Student student2 = new Student("Adam Smith", "12/11/1979" , new Address("Ivy Hill",67,"Belfast", "BT17 7BN", "Co.Antrim"),StudentMode.Parttime, true);
ArrayList<Person> uniPeople = new ArrayList<Person>();
uniPeople.add(student1);
uniPeople.add(student2);
printMenu(uniPeople);
}
public static void printAllDetails(ArrayList<Person> uniPeople) {
for (int i = 0; i < uniPeople.size(); i++) {
System.out.println(uniPeople.get(i).toString());
}
}
}
Output:
Student [ ID: 1002; Name: null; DOB: null; Study Mode: Fulltime; Number of Enrolled Modules: 0
Student [ ID: 1003; Name: null; DOB: null; Study Mode: Parttime; Number of Enrolled Modules: 0
Can anyone help me with this problem? Thanks
public Person(String name, String dob, Address address) {
super();
LAST_ID ++;
this.id = LAST_ID;
}
The constructor completely ignores its three arguments. It doesn't assign them to the corresponding fields, so these fields keep their default value: null.
You have to store the name value in the constructor. Your version did not use the name value.
public Person(String name, String dob, Address address) {
super();
this.name = name; // <== important line
this.dob = dob; // <== important line
this.address = address; // <== important line
LAST_ID ++;
this.id = LAST_ID;
}
Look at the constructor in person and in student, Should use the parameters in the method header.
super(name,dob,address)
this is my current code to store rooms(it compiles fine) but in the UML there is a variable called addEquipment and there is also another class called Equipment to be defined. I'm having trouble wrapping my head around what I'm supposed to do with this. Am I supposed to create and call an object called Equipment? what goes in addEquipment?
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private String equipmentList;
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public String getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(String anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
}
//Create room object
public Room(int capacity, String equipmentList) {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
return "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
}
}
You can create a new class Equipment and modify your attribute equipmentList to be a List:
public class Equipment {
private String name;
public Equipment(String name) {
this.name = name;
}
}
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private List<Equipment> equipmentList = new ArrayList<Equipment>();
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public List<Equipment> getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(List<Equipment> anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
Equipment oneEquipment = new Equipment(newEquipment);
equipmentList.add(oneEquipment);
}
//Create room object
public Room() {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
String capacity=String.valueOf(getCapacity());
String room = "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
return room;
}
}
In the method addEquipment, you can create a new Equipment and add it to equipmentList, like code above.
An Equipment class could be anything. Lets assume the "Equipment"-class has a String called "name" as it's attribute
public class Equipment {
String name;
public Equipment( String name) {
this.name = name;
}
public String getName() {
return this.name
}
}
When you extend your Room class by the requested "addEquipment" method, you can do something like this.
public class Room {
... // Your code
private int equipmentIndex = 0;
private Equipment[] equipment = new Equipment[10]; // hold 10 Equipment objects
public void addEquipment( Equipment eq ) {
if ( equipmentIndex < 10 ) {
equipment[ equipmentIndex ] = eq;
equipmentIndex++;
System.out.println("Added new equipment: " + eq.getName());
} else {
System.out.println("The equipment " + eq.getName() + " was not added (array is full)");
}
}
}
Now when you call
room.addEquipment( new Equipment("Chair") );
on your previously initialized object of the Room-class, you will get
"Added new equipment: Chair"
Hope this helps a bit.
PS: The code is untestet (maybe there hides a syntax error somewhere)
I am fairly new to Inheritance, and I'm not sure if I am doing it right but I seem to be on the right track. The program runs fine except the output I am getting isn't right. I think the problem is to do with my constructors.
public class Person {
protected static String name;
protected static int birthYear;
public Person(String name, int birthYear) {
}
public String name (String n) {
n = name;
return n;
}
public int birthYear (int bY) {
bY = birthYear;
return bY;
}
#Override
public String toString() {
return String.format(name + birthYear);
}
}
public class Student extends Person {
protected String major;
public Student(String name, int birthYear, String major) {
super(name, birthYear);
major = "";
}
public String major(String maj) {
maj = major;
return maj;
}
public String toString() {
super.toString();
return super.toString() + major;
}
}
public class Instructor extends Person {
protected static int salary;
public Instructor(String name, int birthYear, int salary) {
super(name, birthYear);
salary = 0;
}
public int salary(int sal) {
sal = salary;
return sal;
}
public String toString() {
super.toString();
return super.toString() + salary;
}
}
public class PersonTester {
public static void main(String[] args) {
Person p = new Person("Perry", 1959);
Student s = new Student("Sylvia", 1979, "Computer Science");
Instructor e = new Instructor("Edgar", 1969, 65000);
System.out.println(p);
System.out.println("Expected: Person[name=Perry,birthYear=1959]");
System.out.println(s);
System.out.println("Expected:" +
"Student[super=Person[name=Sylvia,birthYear=1979],major=Computer]");
System.out.println(e);
System.out.println("Expected:" + "Instructor[super=Person[name=Edgar,birthYear=1969],salary=65000.0]");
}
}
OUTPUT I AM GETTING:
null0
Expected: Person[name=Perry,birthYear=1959]
null0null
Expected: Student[super=Person[name=Sylvia,birthYear=1979],major=Computer Science]
null00
Expected: Instructor[super=Person[name=Edgar,birthYear=1969],salary=65000.0]
Try changing your constructor in Person to:
public Person(String name, int birthYear) {
this.name = name;
this.birthYear = birthYear;
}
Currently, the constructor has an empty body, so when you call super(name, birthYear); in the subclass constructor, nothing actually happens.
Your Student constructor also has an error. You forgot to initialize the major field.
public Student(String name, int birthYear, String major) {
super(name, birthYear);
this.major = major;
}
You have the same problem in the Instructor constructor...
public Instructor(String name, int birthYear, int salary) {
super(name, birthYear);
this.salary = salary;
}
Finally, you need to take away the static keywords before the fields in Person. This is because static ensures, that there will always be one (and only one) instance of those fields per class, as opposed to one per instance, like you want it to be:
protected String name;
protected int birthYear;
Same thing for the salary field in Instructor.
n = name; this causing your problem. It must be name = n;. All your setter function contain this problem, correct them all and tell me result.