简体   繁体   English

根据用户输入创建元素的子列表

[英]create a sub list of elements based on user input

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.我写了下面的代码,从一个初始化的国家列表中,该方法将返回所有经度 >= 5 的国家,该代码有效,但现在我希望该方法返回接近字符串 D 的国家的名称在经度 5 度范围内。

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.我尝试实现如下所示的扫描仪,但我仍然得到经度高于 5 的国家/地区。如何使该方法根据用户输入返回国家/地区名称。

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

Correct your if statement.更正您的 if 语句。

You are writing following ...您正在编写以下...

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

The "country.CountryName.equals(D)" part returns true or false. “country.CountryName.equals(D)”部分返回真或假。 So you are checking if CountriesDistance not contains true/false AND if the longitude of the country is greater or equal to 5.因此,您正在检查国家距离是否不包含真/假以及国家的经度是否大于或等于 5。

I guess you ment:我猜你会说:

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

I initialized baseCountry like this:我像这样初始化了 baseCountry:

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:在这种情况下,我通过调用 getName() 获得了国家的名称,我是这样实现的:

class Country {

    String countryName;

    public String getName() {
        return countryName;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM