今天开始学Java 给定n个字符串,请对n个字符串按照字典序排列。

题目描述

给定n个字符串,请对n个字符串按照字典序排列。

输入描述:

输入第一行为一个正整数n(1≤n≤1000),下面n行为n个字符串(字符串长度≤100),字符串中只含有大小写字母。

输出描述:

数据输出n行,输出结果为按照字典序排列的字符串。
示例1

输入

9
cap
to
cat
card
two
too
up
boat
boot

输出

boat
boot
cap
card
cat
to
too
two
up

import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
             long n = sc.nextInt();
            //其实这里也可以直接用数组,然后用Arrays.sort()
             List<String> list = new ArrayList<String>();
            for(int i=0;i<n;i++){
            //这里之前用的nextLine()就不行,提示错误,看了讨论说是因为前面的nextInt没有读第一行的换行符
                String b = sc.next();
                list.add(b);
            }
            Collections.sort(list);
          
           for(String st:list){
               System.out.println(st);
           }
           
        }
    }
}

猜你喜欢

转载自blog.csdn.net/u014566193/article/details/79691826
今日推荐