博客
关于我
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/

你可能感兴趣的文章
Nginx配置实例-负载均衡实例:平均访问多台服务器
查看>>
NIFI大数据进阶_连接与关系_设置数据流负载均衡_设置背压_设置展现弯曲_介绍以及实际操作---大数据之Nifi工作笔记0027
查看>>
Nio ByteBuffer组件读写指针切换原理与常用方法
查看>>
NIO Selector实现原理
查看>>
nio 中channel和buffer的基本使用
查看>>
NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
查看>>
NI笔试——大数加法
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No module named cv2
查看>>