使用for-each循环搜索arraylist中的字符串

时间:2018-04-03 01:33:53

标签: java arraylist foreach

所以我想使用for-each循环在我的arraylist中搜索,以便找到输入的国家的首都,搜索也不区分大小写。我的另一个类中的arraylist名称是ElementsList。下面是Country()类中包含大写字母的代码:

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


}

我遇到的问题是创建for-each循环来搜索正在使用的国家的首都。它并不多,但这是我到目前为止所得到的:

   public String searchForCapital(String countryName){

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


   }

1 个答案:

答案 0 :(得分:0)

您的for each是对的。这是搜索资本的完整功能,请注意,您必须拥有elementsListCountry个对象的数组列表

public String searchForCapital(String countryName) {

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