boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

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


avatar
作者 2025年9月15日 8

使用多重条件排序: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 对应一种排序方式。

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

无限画

千库网旗下AI绘画创作平台

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

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

示例代码:

// ... (代码见上文) ... 

代码解释:

立即学习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 语句的用法。 同时,要注意输入验证和代码可读性,以提高程序的健壮性和可维护性。



评论(已关闭)

评论已关闭