如何重置对象循环“计数器”?
Posted
技术标签:
【中文标题】如何重置对象循环“计数器”?【英文标题】:How do i reset Object loop "counter"? 【发布时间】:2021-12-09 15:48:19 【问题描述】:如何在“if”语句为真后重新设置“city”对象并重新启动“for”语句?
private SortedSet<City> cityList;
for(City city:this.cityList)
if(city.getPopulation()==arr[i])
System.out.printf(city.getName() + "(" + city.getCountry() + ") population: " + city.getPopulation() + " area: " + city.getArea());
i++;
【问题讨论】:
您使用了不同类型的循环。增强的 for 循环对您隐藏了它的迭代器,因此您无法重置它。 @azurefrog 如何将循环转换为带有 i 计数器的循环? 【参考方案1】:这是你想要完成的吗?
import java.util.Set;
public class City
public static void main(String[] args)
Integer[] arr = 50_000, 100_000, 200_000 ;
Set<City> cityList = Set.of( //
new City(100_000, "city1", "country1", "area1"), //
new City(200_000, "city2", "country2", "area2"), //
new City(350_000, "city3", "country3", "area3") //
);
outer: for (int i = 0; i < arr.length; i++)
for (City city : cityList)
if (city.getPopulation() == arr[i])
System.out.println(city.getName() + "(" + city.getCountry() + ") population: "
+ city.getPopulation() + " area: " + city.getArea());
continue outer;
private int population;
private String name;
private String country;
private String area;
public City(int population, String name, String country, String area)
this.population = population;
this.name = name;
this.country = country;
this.area = area;
public int getPopulation()
return population;
public void setPopulation(int population)
this.population = population;
public String getName()
return name;
public void setName(String name)
this.name = name;
public String getCountry()
return country;
public void setCountry(String country)
this.country = country;
public String getArea()
return area;
public void setArea(String area)
this.area = area;
嵌套循环时,您可以为它们添加标签 (https://www.tutorialspoint.com/break-continue-and-label-in-Java-loop)
【讨论】:
谢谢!终于工作了。 再想一想,你甚至不需要标签。您可以通过替换“继续外部”来“打破”内部循环;使用“break”并删除“outer:”标签以上是关于如何重置对象循环“计数器”?的主要内容,如果未能解决你的问题,请参考以下文章