因此,当我创建具有多个类的变量参数时遇到问题。正如您在下面的代码中看到的那样,我只是试图以随机顺序进入多个城市和地区,并尝试打印出整个州的人口。除了这个问题,我不知道如何遍历CAndD数组以将所有种群加在一起。
代码:
import requests
from requests.auth import HTTPBasicAuth
requests.get("http://google.com:8070/api/v2/organizations",auth=HTTPBasicAuth('user', 'pass'))
如果有人可以帮助我解决这个问题,那就太好了!
答案 0 :(得分:1)
请看下面的代码,我将人口变量从城市和地区移到了父类:
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;
}
}
答案 1 :(得分:0)
设计一个空的父类似乎不好。在您的代码中,类City和District相同。我假设您想知道地点的类型(城市或地区)。更好的解决方案是将子类的所有属性移到父类。 CitiesAndDistricts类为:
class CitiesAndDistricts {
String name;
int population;
public CitiesAndDistricts(String name, int population} {
this.name = name;
this.population = population;
}
}
从该父类中,您可以扩展到以下城市和地区类:
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);
}
}