有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

循环在Java中对句子进行排序,而不使用数组

我希望能够对句子样本输入进行排序Python:PHP:C++:C:Java:HTML

不使用数组或数组方法对句子排序

输出应该是这样的

Top programming languages in alphabetical order:
1. C
2. C++
3. HTML
4. Java
5. PHP
6. Python

这是我开始使用的,但我被卡住了,在互联网上找不到任何不使用数组的东西

import java.util.*;

public class SortProgram {
    public static void main(String[] args) {
        // Declare Variables
        String topLang = "";
        int separator = 0;
        String holder = "";
        String top = "";

        // Create a Scanner object attached to the keyboard
        Scanner input = new Scanner(System.in);

        // input
        System.out.print("Enter a list of the top programming languages: ");
        topLang = input.next();

        // separate each word
        while (topLang.length() > 0) {
            separator = topLang.indexOf(":");
            holder = topLang.substring(0, separator);
            topLang = topLang.substring(separator, topLang.length());
            
        }

        System.out.println("  Position Language");
        System.out.println("==========================");
    }

}

共 (1) 个答案

  1. # 1 楼答案

    下面是另一个使用PriorityQueue和regex的解决方案

    try (Scanner scanner = new Scanner(System.in)) {
        Queue<String> sortedLanguages = new PriorityQueue<>();
        System.out.print("Enter a list of the top programming languages: ");
        String input = scanner.next();
        Matcher matcher = Pattern.compile("[^:]+").matcher(input);
        while (matcher.find()) {
            sortedLanguages.add(matcher.group());
        }
        System.out.print("Top programming languages in alphabetical order:");
        for (int i = 1, size = sortedLanguages.size(); i <= size; i++) {
            System.out.printf("\n%d. %s", i, sortedLanguages.poll());
        }
    }