【问题标题】:Using a for-each loop to search for strings in an arraylist使用 for-each 循环在数组列表中搜索字符串
【发布时间】:2018-04-03 01:33:53
【问题描述】:

所以我想使用 for-each 循环在我的数组列表中进行搜索,以便找到输入的国家/地区的首都,而且搜索不区分大小写。我的另一个类中的数组列表名称是 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)){


   }

【问题讨论】:

  • 那么您具体遇到的问题是什么?
  • 另外,你是整个国家级的吗?我实际上并没有在任何地方看到 getCountry() 方法。
  • 不,它不是整个国家类,这里我将放入 getcountry() 方法

标签: java arraylist foreach


【解决方案1】:

您的for each 是对的。这是搜索大写的完整功能,注意你必须有elementsListCountry对象的数组列表

public String searchForCapital(String countryName) {

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    相关资源
    最近更新 更多