首页 > Java > java教程 > 正文

使用多重条件排序:Java 中的字符串分割与 Switch 语句应用

霞舞
发布: 2025-09-14 22:14:01
原创
653人浏览过

使用多重条件排序:java 中的字符串分割与 switch 语句应用

本文旨在指导开发者如何使用 Java 中的字符串分割功能,结合 Switch 语句,实现基于用户输入的多个条件对数据进行排序。文章将详细介绍如何接收用户输入的排序条件,分割字符串,并根据不同的条件进行排序操作,从而实现灵活的数据排序功能。

在实际开发中,经常会遇到需要根据用户指定的多个条件对数据进行排序的场景。 例如,一个英雄数据库,用户可能希望先按姓名排序,然后在姓名相同的情况下按身高排序。 本文将介绍如何使用 Java 实现这一功能,主要涉及字符串分割和 switch 语句的应用。

接收用户输入并分割字符串

首先,需要接收用户输入的排序条件。 通常,用户会输入代表不同排序方式的数字或关键词,并用空格分隔。 可以使用 Scanner 类来读取用户输入,然后使用 String.split() 方法将输入字符串分割成字符串数组

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class Sorter {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("""
                1. Sort by name.
                2. Sort by height.
                3. Sort by power(s).
                4. Sort by weakness(ess).
                5. Sort by origin FROM earth.
                6. Sort by origin NOT from earth.
                """);

        System.out.println("Enter the sorting criteria (e.g., 1 2):");
        String userInput = sc.nextLine().toLowerCase();

        String[] userInputs = userInput.split(" ");

        List<Superhero> superheroes = new ArrayList<>();
        superheroes.add(new Superhero("Superman", 190, "Flight", "Kryptonite", true));
        superheroes.add(new Superhero("Batman", 180, "Intelligence", "None", false));
        superheroes.add(new Superhero("Wonder Woman", 183, "Strength", "Piercing Weapons", true));
        superheroes.add(new Superhero("Flash", 180, "Speed", "Cold", true));

        List<Superhero> sortedSuperheroes = sortByTwoCriteria(superheroes, userInputs);

        for (Superhero superhero : sortedSuperheroes) {
            System.out.println(superhero);
        }

        sc.close();
    }

    public static List<Superhero> sortByTwoCriteria(List<Superhero> superheroes, String[] userInputs) {
        if (userInputs.length == 0) {
            System.out.println("No sorting criteria provided.");
            return superheroes;
        }

        Comparator<Superhero> comparator = null;

        for (String input : userInputs) {
            Comparator<Superhero> currentComparator = switch (input) {
                case "1" -> Comparator.comparing(Superhero::getName);
                case "2" -> Comparator.comparingInt(Superhero::getHeight);
                case "3" -> Comparator.comparing(Superhero::getPower);
                case "4" -> Comparator.comparing(Superhero::getWeakness);
                case "5" -> Comparator.comparing(Superhero::isFromEarth);
                case "6" -> Comparator.comparing(Superhero::isFromEarth).reversed();
                default -> {
                    System.out.println("Invalid sorting criteria: " + input);
                    yield null; // or throw an exception
                }
            };

            if (currentComparator != null) {
                if (comparator == null) {
                    comparator = currentComparator;
                } else {
                    comparator = comparator.thenComparing(currentComparator);
                }
            }
        }

        if (comparator != null) {
            superheroes.sort(comparator);
        }

        return superheroes;
    }
}

class Superhero {
    private String name;
    private int height;
    private String power;
    private String weakness;
    private boolean fromEarth;

    public Superhero(String name, int height, String power, String weakness, boolean fromEarth) {
        this.name = name;
        this.height = height;
        this.power = power;
        this.weakness = weakness;
        this.fromEarth = fromEarth;
    }

    public String getName() {
        return name;
    }

    public int getHeight() {
        return height;
    }

    public String getPower() {
        return power;
    }

    public String getWeakness() {
        return weakness;
    }

    public boolean isFromEarth() {
        return fromEarth;
    }

    @Override
    public String toString() {
        return "Superhero{" +
                "name='" + name + '\'' +
                ", height=" + height +
                ", power='" + power + '\'' +
                ", weakness='" + weakness + '\'' +
                ", fromEarth=" + fromEarth +
                '}';
    }
}
登录后复制

代码解释:

立即学习Java免费学习笔记(深入)”;

  1. 接收用户输入: 使用 Scanner 类读取用户输入的字符串。
  2. 分割字符串: 使用 userInput.split(" ") 将用户输入的字符串按空格分割成字符串数组 userInputs。
  3. 遍历排序条件: 循环遍历 userInputs 数组,对每个排序条件进行处理。
  4. 构建Comparator: 使用Comparator链式调用实现多重排序,如果当前条件对应的Comparator不为空,则将其添加到链式Comparator中。
  5. 进行排序: 最后,使用 superheroes.sort(comparator) 方法对列表进行排序。

使用 switch 语句进行排序

switch 语句可以根据用户输入的排序条件,执行相应的排序操作。 每个 case 对应一种排序方式。

AppMall应用商店
AppMall应用商店

AI应用商店,提供即时交付、按需付费的人工智能应用服务

AppMall应用商店 56
查看详情 AppMall应用商店

示例代码:

// ... (代码见上文) ...
登录后复制

代码解释:

立即学习Java免费学习笔记(深入)”;

  1. switch 语句: 根据 input 的值,执行不同的 case 分支。
  2. case 分支: 每个 case 分支对应一种排序方式,例如按姓名、身高、力量等。
  3. Comparator.comparing(): 使用 Comparator.comparing() 方法创建一个比较器,用于指定排序的依据。
  4. superheroes.sort(comparator): 使用 Collections.sort() 方法,根据指定的比较器对列表进行排序。

注意事项

  • 输入验证: 在实际应用中,需要对用户输入进行验证,确保输入的排序条件是有效的。 可以使用 try-catch 语句捕获 NumberFormatException 等异常,并给出相应的提示。
  • 排序顺序: 可以使用 Comparator.reverseOrder() 方法实现降序排序。
  • 多重排序: Comparator.thenComparing()方法可以实现多重排序,即先按照第一个条件排序,然后在第一个条件相同的情况下,按照第二个条件排序。
  • 代码可读性 为了提高代码可读性,可以将排序逻辑封装成单独的方法。

总结

本文介绍了如何使用 Java 中的字符串分割功能和 switch 语句,实现基于用户输入的多个条件对数据进行排序。 通过灵活运用这些技术,可以构建出功能强大、易于使用的排序工具。 关键在于理解字符串分割的原理,以及 switch 语句的用法。 同时,要注意输入验证和代码可读性,以提高程序的健壮性和可维护性。

以上就是使用多重条件排序:Java 中的字符串分割与 Switch 语句应用的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号