用java写一个 递归查询 省市区
时间: 2023-06-04 08:02:27 浏览: 727
地区表MySql递归sql脚本
好的,您可以使用以下代码实现递归查询省市区:
```
public class Address {
private String province;
private String city;
private String district;
public Address(String province, String city, String district) {
this.province = province;
this.city = city;
this.district = district;
}
// 递归查询省市区
public void getAddress(Address address) {
if (address != null) {
System.out.println(address.province + "-" + address.city + "-" + address.district);
getAddress(address.getSubAddress());
}
}
// 获取下一级地址
public Address getSubAddress() {
if (district != null) {
return null;
} else if (city != null) {
return new Address(province, city, null);
} else if (province != null) {
return new Address(province, null, null);
} else {
return null;
}
}
}
```
您可以通过创建Address对象并传入省市区信息来进行查询,如下所示:
```
Address beijing = new Address("北京市", "北京市", "西城区");
beijing.getAddress(beijing);
```
输出结果为:
```
北京市-北京市-西城区
北京市-北京市
北京市
```
希望能帮到您!
阅读全文