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

如何使用String.equals与String.compareTo对输入姓名排序并处理重复

Java: Sort Names Alphabetically & Detect Duplicates with equals() and compareTo()

Hey there! Let's walk through how to solve this problem—sorting user-input names alphabetically using String.equals() and String.compareTo(), while also catching duplicates and showing clear error messages. Here's a practical, step-by-step solution:

Core Logic Overview

First, we'll collect all user-input names, then check for duplicates using String.equals(). If duplicates exist, we'll print specific error messages. If no duplicates are found, we'll sort the names lexicographically using String.compareTo() and output the sorted list.

Complete Code Implementation

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

public class NameSorter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<String> names = new ArrayList<>();
        final int TOTAL_NAMES = 3; // Adjust this number for more/less inputs

        // Gather user input
        for (int i = 1; i <= TOTAL_NAMES; i++) {
            System.out.print("输入姓名" + i + ":");
            String inputName = scanner.nextLine().trim();
            names.add(inputName);
        }

        // Check for duplicate names
        boolean duplicatesFound = false;
        for (int i = 0; i < names.size(); i++) {
            for (int j = i + 1; j < names.size(); j++) {
                if (names.get(i).equals(names.get(j))) {
                    System.out.println("姓名" + (i + 1) + "和姓名" + (j + 1) + "重复。");
                    duplicatesFound = true;
                    // Uncomment below if you only need to report the first duplicate
                    // break;
                }
            }
            // if (duplicatesFound) break;
        }

        // Sort and print names if no duplicates
        if (!duplicatesFound) {
            // Manual bubble sort using String.compareTo()
            for (int i = 0; i < names.size() - 1; i++) {
                for (int j = 0; j < names.size() - i - 1; j++) {
                    // Swap if current name comes after the next one alphabetically
                    if (names.get(j).compareTo(names.get(j + 1)) > 0) {
                        String temp = names.get(j);
                        names.set(j, names.get(j + 1));
                        names.set(j + 1, temp);
                    }
                }
            }

            // Output sorted list
            System.out.println("按字母顺序排序后的姓名:");
            for (String name : names) {
                System.out.println("- " + name);
            }
        }

        scanner.close();
    }
}

Key Details Explained

  • String.equals() for Duplicates: This method checks if two strings have identical character sequences (note: it's case-sensitive—so "Alexis" and "alexis" are treated as different. Use equalsIgnoreCase() if you want case-insensitive checks).
  • String.compareTo() for Sorting: This method returns:
    • A negative number if the first string comes before the second alphabetically
    • 0 if the strings are identical
    • A positive number if the first string comes after the second
      We use this to drive our bubble sort, swapping elements until the list is in order.
  • Flexibility: The TOTAL_NAMES constant lets you easily adjust how many names the user can input—no need to rewrite core logic.

Test Cases

Case 1: Duplicate Names

输入姓名1:Alexis
输入姓名2:Alexis
输入姓名3:Katie
输出:姓名1和姓名2重复。

Case 2: No Duplicates

输入姓名1:Katie
输入姓名2:Alexis
输入姓名3:Bob
输出:
按字母顺序排序后的姓名:

  • Alexis
  • Bob
  • Katie

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 06:43:32