Home > Net >  How do i reset Object loop "counter"?
How do i reset Object loop "counter"?

Time:12-10

How i can reset the "city" object and start the "for" statement from the start again after the "if" statement is true?

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  ;
            }
        }

CodePudding user response:

Is this what you want to accomplish?

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;
    }

}

When nesting loops you can add a label to them (https://www.tutorialspoint.com/break-continue-and-label-in-Java-loop)

  • Related