用java写一段程序:有省市区数据,每个区有设备,形成树形结构,并统计省市区设备数量
时间: 2023-03-24 18:02:26 浏览: 59
很高兴回答你的问题。以下是用 Java 编写的程序,可以实现对省市区设备数量的统计和树形结构的构建:
```
import java.util.*;
class Device {
String name;
int count;
List<Device> children;
public Device(String name, int count) {
this.name = name;
this.count = count;
this.children = new ArrayList<>();
}
public void addChild(Device child) {
this.children.add(child);
}
public int getCount() {
int sum = this.count;
for (Device child : children) {
sum += child.getCount();
}
return sum;
}
public String toString() {
return this.name + " (" + this.getCount() + ")";
}
}
public class Main {
public static void main(String[] args) {
Map<String, Map<String, Map<String, Integer>>> data = new HashMap<>();
data.put("广东省", new HashMap<>());
data.get("广东省").put("深圳市", new HashMap<>());
data.get("广东省").put("广州市", new HashMap<>());
data.get("广东省").get("深圳市").put("南山区", 100);
data.get("广东省").get("深圳市").put("福田区", 200);
data.get("广东省").get("广州市").put("天河区", 150);
data.get("广东省").get("广州市").put("越秀区", 180);
List<Device> devices = new ArrayList<>();
for (String province : data.keySet()) {
Device provinceDevice = new Device(province, );
for (String city : data.get(province).keySet()) {
Device cityDevice = new Device(city, );
for (String district : data.get(province).get(city).keySet()) {
int count = data.get(province).get(city).get(district);
Device districtDevice = new Device(district, count);
cityDevice.addChild(districtDevice);
}
provinceDevice.addChild(cityDevice);
}
devices.add(provinceDevice);
}
for (Device device : devices) {
System.out.println(device);
for (Device child : device.children) {
System.out.println(" " + child);
for (Device grandchild : child.children) {
System.out.println(" " + grandchild);
}
}
}
}
}
```
这个程序中,我们首先定义了一个 `Device` 类,表示一个设备。每个设备有一个名称和一个数量,还有一个子设备列表。我们可以通过 `addChild` 方法向一个设备添加子设备,通过 `getCount` 方法统计设备数量。
然后,我们定义了一个 `Main` 类,其中包含了一个 `main` 方法。在这个方法中,我们首先定义了一个 `data` 变量,表示省市区数据。这个变量是一个嵌套的 `Map`,其中第一层的键是省份名称,第二层的键是城市名称,第三层的键是区县名称,值是设备数量。
接下来,我们遍历 `data` 变量,将每个省份、城市、区县都转换成一个 `Device` 对象,并将它们按照树形结构连接起来。最后,我们遍历所有的设备,输出它们的名称和数量。
希望这个程序能够帮助你解决问题。如果你有任何疑问,欢迎随时联系我。