博客
关于我
7-8 英文单词排序 (25 分)
阅读量:625 次
发布时间:2019-03-12

本文共 2017 字,大约阅读时间需要 6 分钟。

为了完成这个任务,我们需要编写一个Java程序,该程序可以从标准输入中读取英文单词,并将它们按长度排序。如果两个单词的长度相同,则按它们的出现顺序输出。这个任务可以通过使用Java的小程序框架来实现。

步骤一:读取输入

我们从标准输入读取数据,直到遇到标志性字符'#'。在读取过程中,我们将每个单词存储在一个字符串列表中。

import java.util.ArrayList;import java.util.Comparator;import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        ArrayList
words = new ArrayList<>(); while (scanner.hasNext("#")) { String word = scanner.next(); words.add(word); }

步骤二:自定义排序逻辑

我们需要按照单词的长度进行排序。如果两个单词的长度相同,则保持它们在输入时的相对顺序。为此,我们可以定义一个自定义的比较器。

words.sort((w1, w2) -> {    int len1 = w1.length();    int len2 = w2.length();        // 如果一个单词的长度小于另一个,放在前面    if (len1 != len2) {        return Integer.compare(len1, len2);    }        // 如果长度相同,按出现顺序排列    return words.indexOf(w1) - words.indexOf(w2);});

步骤三:输出结果

排序完成后,我们将结果依次输出到标准输出,每个单词后面跟一个空格。

for (String word : words) {    System.out.println(word + " ");}

步骤四:完整的代码

综上所述,完整的Java程序如下:

import java.util.ArrayList;import java.util.Comparator;import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        ArrayList
words = new ArrayList<>(); while (scanner.hasNext("#")) { String word = scanner.next(); words.add(word); } // 自定义排序逻辑 words.sort((w1, w2) -> { int len1 = w1.length(); int len2 = w2.length(); // 先比较长度 if (len1 != len2) { return Integer.compare(len1, len2); } // 长度相同,按输入顺序排列 return words.indexOf(w1) - words.indexOf(w2); }); // 输出排序后的结果 for (String word : words) { System.out.println(word + " "); } }}

Pedido de responsabilidade

Espero que este programa cumpra com os requisitos especificados. Caso haja algum erro ou necessidade de ajustes, por favor, informe-me.

转载地址:http://bmwaz.baihongyu.com/

你可能感兴趣的文章
python读取json数据的id_python处理JSON数据
查看>>
Python 中的Duck Typing
查看>>
Python 中的for in 遍历生成字典、添加判断条件if
查看>>
Python 中的Lock与RLock
查看>>
Python 中的range(),arange()函数
查看>>
Python 中的内存管理机制
查看>>
Python 中的函数包装器:模型运行时和调试
查看>>
Python 中的列表理解和 lambda
查看>>
Python 中的多层for in嵌套循环使用
查看>>
Python 中的多线程(01/4)
查看>>
Python 中的多进程(01/2):简介
查看>>
Python 中的多进程(02/2):进程之间的通信)
查看>>
Python 中的字符串、列表、元组和字典数据类型的特点和使用场景
查看>>
Python 中的属性访问器是什么?如何使用 @property 装饰器?
查看>>
Python 中的带宽限制
查看>>
Python 中的机器学习简介:多项式回归
查看>>
python读取grib2数据_用Python加载grib2文件
查看>>
Python 中的注意点_s2
查看>>
Python读取Excel的几种工具包(附Demo)
查看>>
Python 中的生成器是什么?
查看>>