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

Java开发:如何对用户输入填充的ArrayList元素进行手动偏好排名

解决方案:基于两两比较的动态元素排名实现

针对你需要通过两两比较完成任意数量元素排名的需求,可以采用插入排序式的比较逻辑——逐个将未排名元素与已完成排名的元素进行对比,确定其在有序列表中的位置。这种方式适配任意数量的输入元素,且逻辑清晰易实现。

核心逻辑步骤

  • 若输入元素数量≤1,直接输出结果(无需排名)。
  • 初始化已排序列表,先放入第一个元素。
  • 遍历剩余未排名元素,对每个元素:
    • 从已排序列表的头部开始,逐个与当前元素进行两两比较。
    • 根据用户选择的偏好,确定当前元素应插入的位置。
    • 将元素插入到已排序列表的对应位置,完成该元素的排名。

修改后的完整代码

//Ranking.java是一个用于提示用户输入一组相关元素
//并存储到数组中的程序。程序随后会提示用户将
//这些元素从优到劣排名并输出结果

//import Scanner and ArrayList
import java.util.*;

//declare class
public class Ranking {

    //declare main method
    public static void main(String[] args) {
        
        //initialize scanner
        Scanner input = new Scanner(System.in);
        
        //create ArrayList to store items
        ArrayList<String> items = new ArrayList<String>();
        
        //introduction
        System.out.println("Welcome to Ranking.java!");
        
        //while loop that repeats the prompt unless the user enters "STOP"
        while(true) {
            //prompt
            System.out.print("\nPlease enter an item you wish to add to the ranking list, "
                    + "or type 'STOP' to end the program.\n>> ");

            //stored in item variable
            String item = input.nextLine().trim();
            
            //if item equals "STOP," program breaks and prints out the list of items entered
            if(item.equalsIgnoreCase("STOP")) {
                System.out.println("\nYou have entered:");
                for(String i : items) {
                    System.out.println("- " + i);
                }
                break;
            }
            //otherwise it adds to the ArrayList, skip empty input
            else if(!item.isEmpty()) {
                items.add(item);
            }
        }
        
        //Handle case with no or single item
        if(items.size() <= 1) {
            System.out.println("\nFinal ranking:");
            for(String i : items) {
                System.out.println(i);
            }
            input.close();
            return;
        }
        
        ArrayList<String> itemsRanked = new ArrayList<String>();
        //Initialize ranked list with first item
        itemsRanked.add(items.get(0));
        
        //ranking introduction
        System.out.println("\nYou may now rank the following from greatest to least.");
        System.out.println("For each comparison, enter the number corresponding to your preference:\n");
        
        //Process remaining items
        for(int i = 1; i < items.size(); i++) {
            String currentItem = items.get(i);
            System.out.println("Now ranking: " + currentItem);
            
            //Find the correct position to insert currentItem
            int insertIndex = 0;
            while(insertIndex < itemsRanked.size()) {
                String rankedItem = itemsRanked.get(insertIndex);
                //Prompt user for comparison
                System.out.println("\n1. " + rankedItem);
                System.out.println("2. " + currentItem);
                System.out.print("Which do you prefer? Enter 1 or 2: ");
                
                String choice = input.nextLine().trim();
                //Validate input
                while(!choice.equals("1") && !choice.equals("2")) {
                    System.out.print("Invalid input. Please enter 1 or 2: ");
                    choice = input.nextLine().trim();
                }
                
                if(choice.equals("2")) {
                    //Current item is preferred over rankedItem, insert here
                    break;
                }
                //If prefer rankedItem, move to next position in ranked list
                insertIndex++;
            }
            
            //Insert currentItem at the determined position
            itemsRanked.add(insertIndex, currentItem);
            System.out.println("\nCurrent ranking so far:");
            for(int j = 0; j < itemsRanked.size(); j++) {
                System.out.println((j+1) + ". " + itemsRanked.get(j));
            }
        }
        
        //Output final ranking
        System.out.println("\n=== Final Ranking ===");
        for(int j = 0; j < itemsRanked.size(); j++) {
            System.out.println((j+1) + ". " + itemsRanked.get(j));
        }
        
        input.close();
    }
}

关键代码说明

  1. 输入校验:添加了对空输入的过滤,以及用户选择时的有效性校验,避免程序因非法输入崩溃。
  2. 插入排序逻辑:
    • 每次取一个未排名元素,与已排序列表中的元素依次比较。
    • 若用户偏好当前元素,则将其插入到当前比较位置;若偏好已排名元素,则继续向后比较。
  3. 实时反馈:在每次插入后输出当前排名状态,让用户清晰看到排名进度。

示例运行流程

假设用户输入了3个元素:Star Wars、Harry Potter、The Lord of the Rings,排名阶段会依次进行:

  1. 用Harry Potter和已排名的Star Wars比较,根据选择确定位置。
  2. 用The Lord of the Rings和已排序列表中的元素逐个比较,找到插入位置。
  3. 最终输出完整的排名结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:19:56