簡體   English   中英

使用for-each循環在arraylist中搜索字符串

[英]Using a for-each loop to search for strings in an arraylist

因此,我想使用for-each循環在我的數組列表中進行搜索,以便找到所輸入國家/地區的首都,而且搜索也不區分大小寫。 我的另一個類中的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)){


   }

for each都是對的。 這是搜索資本的完整功能,請注意,您必須具有elementsList數組Country對象的列表

public String searchForCapital(String countryName) {

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM