首页 > 解决方案 > Java method to add variables for each element in an array

问题描述

Working with the UML class diagram below I am trying to add up the population of each Building of type Dwelling and return the sum in The Village getPopulation() method. I am unsure how to proceed in writing the getPopulation() method. Basically, I want to loop over the array of buildings and call the getPopulation method for each building that implements the dwelling interface but I am unsure how to do so.

enter image description here

My classes are:

Dwelling:

interface Dwelling {
  int getNumberOfOccupants();
}

House:

import javafx.scene.canvas.GraphicsContext;
import java.util.Scanner;

public class House extends Building implements Dwelling  {
    private final int occupants;
    private final int bedrooms;

    private House(String name, double xPosition,int bedrooms, int occupants){
        super(name,xPosition);
        this.bedrooms = bedrooms;
        this.occupants = occupants;
    }

    public static House create() {
        Scanner scan = new Scanner(System.in);
        House a;
        System.out.println("Enter name of the House: ");
        String name = scan.nextLine();
        System.out.println("Enter XPosition of the House: ");
        int xPosition = scan.nextInt();
        System.out.println("Enter number of bedrooms: ");
        int bedrooms = scan.nextInt();
        System.out.println("Enter number of occupants: ");
        int occupants = scan.nextInt();

        a = new House(name, xPosition, bedrooms, occupants);
        return a;
    }

    public void draw(GraphicsContext canvas){
    }

    @Override
    public String toString(){
        return "House: " + "bedrooms= " + bedrooms + " occupants= " + occupants + "\n" + super.toString();
    }

    @Override
    public int getNumberOfOccupants() {
        return occupants;
    }
}

ApartmentBuilding:

import javafx.scene.canvas.GraphicsContext;
import java.util.Scanner;

public class ApartmentBuilding extends HighRise implements Dwelling{

    private int occupants;
    private final int occupantsPerFloor;

    private ApartmentBuilding(String name, double xPosition, int numberOfFloors, int occupantsPerFloor){
        super(name, xPosition, numberOfFloors);
        this.occupantsPerFloor = occupantsPerFloor;
    }

    public static ApartmentBuilding create() {
        Scanner scan = new Scanner(System.in);
        ApartmentBuilding a;
        System.out.println("Enter name of the Apartment Building: ");
        String name = scan.nextLine();
        System.out.println("Enter XPosition of the Apartment Building: ");
        int xPosition = scan.nextInt();
        System.out.println("Enter number of floors: ");
        int numberOfFloors = scan.nextInt();
        System.out.println("Enter number of occupants per floor: ");
        int occupantsPerFloor = scan.nextInt();

        a = new ApartmentBuilding(name, xPosition, numberOfFloors, occupantsPerFloor);
        return a;
    }

    public void draw(GraphicsContext canvas){
    }

    @Override
    public String toString(){
        return "Apartment Building: " + "occupantsPerFloor= " + occupantsPerFloor + "\n" + super.toString() + "\n";
    }

    @Override
    public int getNumberOfOccupants() {
        occupants = numberOfFloors * occupantsPerFloor;
        return occupants;
    }
}

Building:

import javafx.scene.canvas.GraphicsContext;

public class Building implements Drawable {
    private final String name;
   private final double xPosition;
    
    public Building(String name, double xPosition){
            this.name = name;
            this.xPosition = xPosition;
    }

    public String getName(){
        return name;
    }

    public void draw(GraphicsContext canvas) {
    }

    public double getXPosition() {
        return xPosition;
    }

    @Override
    public String toString(){
            return "Type... Building:  " + "name= " + getName() + ", xPosition= " + getXPosition() + "\n";}
    }

Village:

import javafx.scene.canvas.GraphicsContext;
import java.util.Scanner;

public class Village{
    public static final double Y_FLOOR = 300;
    private int size;
    private final String villageName;
    private final Building[] buildings;

    private Village(String villageName, int size){
        this.size = size;
        this.villageName = villageName;
        this.buildings = new Building[size];
    }

    public static Village create() {
        Village a;
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter name of village: ");
        String villageName = scan.nextLine();
        int num = 0;
        do {
            System.out.println("Enter number of buildings: ");
            num = scan.nextInt();
            if (num <= 0)
                System.out.println("Input error, cannot enter a negative or zero");
        } while (num <=0);
        a = new Village(villageName, num);
        for(int i = 0; i < num; i++) {
            System.out.println("Enter type of Building: 1= House, 2= Apartment, 3= Store ");
            int choice = scan.nextInt();
            if (choice == 1){
                a.buildings[i] = House.create();
            }
            if (choice == 2){
                a.buildings[i] = ApartmentBuilding.create();
            }
            if (choice ==3){
                a.buildings[i] = Store.create();
            }
            else {
                System.out.println("Please enter a number between 1 and 3");
            }
        }
        return a;
    }

    public int getPopulation(){    
        return size;
    }

    public void draw(GraphicsContext canvas){
    }

    public String toString(){
        String str = "\n"+ "Village of " + villageName + "\n\n";
        for (int i=0; i<buildings.length; i++) {
            str = str + buildings[i].toString() + "\n"; // this adds each buildings information to the string
        }
        return str;
    }
}

标签: javaarraysinterfacepolymorphismabstract-class

解决方案


Start by iterating the buildings. Assuming a Building can be a Dwelling or a Store we will have to check if the Building is a Dwelling and then do a safe cast and use the Dwelling's getNumberOfOccupants method and add them to our total as we go on.

Note: This cast is safe because we checked if building is a Dwelling before doing it.

Village.java

public int getPopulation() {
    int population = 0;
    for (Building building : buildings) {
         if (building instanceof Dwelling) {
             Dwelling dwelling = (Dwelling) building;
             population += dwelling.getNumberOfOccupants();
         }
    }
    return population;
}

推荐阅读