A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

测试题:编写程序,循环接收用户从键盘输入多个字符串,直到输入“end”时循环结束,并将所有已输入的字符串按字典顺序倒序打印。

import java.io.*;

import java.util.*;
public class Test8
{
        public static void main(String[] args)
        {
                System.out.println("请输入字符串:");
                //定义泛型为String的ArrayList集合
                ArrayList<String> al = new ArrayList<String>();
        //读取键盘录入
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String s = null;
        try
        {
        //使用while循环对录入内容进行判断,不为空,进入循环
              while((s=in.readLine())!=null)
              {
              //判断录入的字符串是否为”end“,是,结束循环
                              if(s.equals("end"))
                                      break;
                      //否则将字符串添加到ArrayList集合中
                              al.add(s);
              }
        }
        catch (IOException e)
        {
                throw new RuntimeException("IO异常");
        }
        // 给ArrayList排序,字典倒序
        Collections.sort(al, Collections.reverseOrder());
        // 打印排序后的结果
        System.out.println("排序后结果:");
        Iterator<String> it = al.iterator();
        while(it.hasNext())
        {
        System.out.println(it.next());
        }
        }

}

有点 疑惑 ?结果 运行输入中文的话 不是倒叙 排列
英文 就没问题
???????

2 个回复

倒序浏览
请问哪个是键盘输入语句啊???
回复 使用道具 举报
  1. import java.io.*;
  2. import java.util.*;
  3. class strReverse
  4. {
  5.         public static void main(String[] args)
  6.         {
  7.                 System.out.println("请输入字符串:");
  8.                 //创建字符串接收对象
  9.                 BufferedReader  bur = new BufferedReader(new InputStreamReader(System.in));
  10.                 //建立字符串缓冲区
  11.                 StringBuilder sb = new StringBuilder();
  12.                 String line = null;
  13.                 try
  14.                 {
  15.                         while((line=bur.readLine())!=null)
  16.                         {
  17.                                 if(line.equals("end"))
  18.                                 {
  19.                                         System.out.println("输入结束");
  20.                                         break;
  21.                                 }
  22.                                 else
  23.                                         sb.append(line.toCharArray());
  24.                         }
  25.                        
  26.                 }
  27.                 catch (IOException e )
  28.                 {
  29.                         throw new RuntimeException("IO异常");
  30.                 }
  31.                
  32.                 System.out.println("排序后:"+sb.reverse());
  33.         }
  34. }
复制代码
实现反转,但是需要程序结束之后才能输出结果,这个又该怎么改~
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马