You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用for-each循环在ArrayList中实现不区分大小写的国家首都查询

实现不区分大小写的国家首都搜索(for-each循环版)

没问题,我来帮你搞定这个需求!首先咱们得先把Country类的基础结构调整正确(原代码里的变量定义有语法问题),然后再写搜索逻辑。

第一步:修正并完善Country类

首先把Country类的变量定义和必要的getter方法补全,这样外部才能获取国家名称和首都信息:

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 countryName; // 替换原nCountry,命名更清晰
    private String continent; // 修正原Cont的命名
    private int population; // 假设原代码的"i..."是人口属性,可按需调整
    private String capital; // 新增首都属性,这是咱们搜索需要的核心字段

    // 构造方法,用于创建Country对象
    public Country(String countryName, String continent, int population, String capital) {
        this.countryName = countryName;
        this.continent = continent;
        this.population = population;
        this.capital = capital;
    }

    // 获取国家名称的getter方法
    public String getCountryName() {
        return countryName;
    }

    // 获取首都的getter方法
    public String getCapital() {
        return capital;
    }

    // 其他属性的getter/setter可根据需求添加
}

第二步:用for-each循环实现搜索逻辑

接下来编写搜索代码,核心是用for-each遍历ElementsList,通过不区分大小写的字符串匹配找到对应首都:

import java.util.ArrayList;
import java.util.Scanner;

public class CountrySearchDemo {
    public static void main(String[] args) {
        // 初始化你的ElementsList,添加示例数据
        ArrayList<Country> elementsList = new ArrayList<>();
        elementsList.add(new Country("China", "Asia", 1412000000, "Beijing"));
        elementsList.add(new Country("United States", "North America", 334000000, "Washington, D.C."));
        elementsList.add(new Country("Germany", "Europe", 83240000, "Berlin"));

        // 获取用户输入的国家名称
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入要查找的国家名称:");
        String inputCountry = scanner.nextLine();

        // 用for-each循环遍历搜索
        String targetCapital = null;
        for (Country country : elementsList) {
            // 使用equalsIgnoreCase()忽略大小写比较,完美解决需求
            if (country.getCountryName().equalsIgnoreCase(inputCountry)) {
                targetCapital = country.getCapital();
                break; // 找到匹配项后直接退出循环,提升效率
            }
        }

        // 输出搜索结果
        if (targetCapital != null) {
            System.out.printf("%s的首都是:%s%n", inputCountry, targetCapital);
        } else {
            System.out.printf("抱歉,未找到名为「%s」的国家%n", inputCountry);
        }

        scanner.close();
    }
}

关键知识点说明

  • 不区分大小写匹配:用String.equalsIgnoreCase()方法,它会自动忽略字符串的大小写差异(比如"FRANCE"和"france"会被判定为相等),比手动转成小写再用equals()更简洁可靠。
  • for-each循环:语法for (元素类型 变量名 : 集合),可以轻松遍历ArrayList里的每一个Country对象,代码更简洁易读。
  • 边界处理:考虑了找不到匹配国家的情况,给用户友好的反馈,避免空指针异常。

内容的提问来源于stack exchange,提问作者Nyx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:06:47