Home > front end >  create a sub list of elements based on user input
create a sub list of elements based on user input

Time:10-28

I wrote the code below, where from an initialized list of countries the method will return all the countries who have a longitude of >= 5, the code works but now I want the method to return the name of countries that are close to String D within a 5 degrees range of longitude.

I tried implementing the scanner as shown below but I still get countries that have longitude higher than 5. how can I make the method return the name of countries based on the user input.

ArrayList<String> CountriesDistance= new ArrayList<>(); 
Scanner scanner= new Scanner(System.in);
System.out.print("Enter The Name of a Country: ");  
String D= scanner.nextLine(); 
for(Country country : Countries)
    if (!CountriesDistance.contains(country.CountryName.equals(D)) && country.getLongitude() >= 5)
        CountriesDistance.add(country.CountryName); 
    System.out.println(CountriesDistance);

CodePudding user response:

Correct your if statement.

You are writing following ...

if (!CountriesDistance.contains(country.CountryName.equals(D)) && country.getLongitude() >= 5)

The "country.CountryName.equals(D)" part returns true or false. So you are checking if CountriesDistance not contains true/false AND if the longitude of the country is greater or equal to 5.

I guess you ment:

if(!CountriesDistance.contains(inputCountryAsString) && (country.getLongitude() <= baseCountry.getLongitude()   5 && country.getLongitude() >= baseCountry.getLongitude() - 5))

I initialized baseCountry like this:

Country baseCountry = getCountryByName(countries, inputCountry);
public static Country getCountryByName(Countries countries, String name) {
    Country country = null;
    for (Country c : Countries) {
        if (c.getName().equals(name))
            country = c;
    }
    return country;
}

In this case I got the name of the Country by calling getName() which I implemented like this:

class Country {

    String countryName;

    public String getName() {
        return countryName;
    }
}
  • Related