使用面孔循环在阵列列表中搜索字符串



因此,我想使用for-each循环在我的阵列列表中搜索以找到输入的国家的首都,搜索也不敏感。我的其他类别elementslist中的arraylist名称。以下是包括资本在内的国家/地区的代码:

import java.text.*;
/**
* Write a description of class Country here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Country
{
private String nCountry;
private String Cont;
private int Area;
private double populationNum;
private double GDP;
private String Capital;
public Country (){
    nCountry = "Default";
}
public Country (String name, String continent, int area, double population,
double gdp, String capital){
    nCountry = name;
    Cont = continent;
    Area = area;
    populationNum = population;
    GDP = gdp;
    Capital = capital;
}
 public String getCountry(){
    return nCountry;
}
public String getCapital(){
    return Capital;
}
  public void setCountry(String name){
    nCountry = name;
}

public void setCapital(String capital){
    Capital = capital;
}    

}

我遇到的麻烦是创建搜索所使用国家首都的面孔循环。这并不多,但这就是我到目前为止的:

   public String searchForCapital(String countryName){
    Country cap = new Country();
    cap = null;
    for(Country c : ElementsList){
        if(c.getCountry().equals(countryName)){

   }

您的for each是正确的。这是搜索资本的完整功能,请注意,您必须具有elementsList对象的CC_2数组列表

public String searchForCapital(String countryName) {
    for (Country c : elementsList) {
        if (c.getCountry().equalsIgnoreCase(countryName)) {
            return c.getCapital();
        }
    }
    return null;
}

最新更新