面试 - Java排序程序

时间:2012-11-02 10:54:44

标签: java sorting

编写一个java程序来读取文件中的输入并对单词进行排序,然后再对整个文件进行排序。 我已正确编码,输入从文件中完全读取,但仍无法完全分割。

请建议我在较短的时间内解决这个问题的正确解决方案..

代码:

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;

public class HariPriya {

    public static void main(String[] ags)throws Exception
    {
        long st=System.currentTimeMillis();
        int v=0;
        String line;
        List ls=new ArrayList();
        //To read data from file
        BufferedReader in=new BufferedReader(new FileReader("D:/hari3.txt"));
        System.out.println("The original text is:");
        while((line = in.readLine())!= null)
        {
          System.out.println(line);  

        }
        String read=line.toLowerCase();
        //Spliting the string based on spaces
        String[] sp=read.replaceAll("[-+.^:,!@#$%&*()~?]","").split(" ");
        for(int i=0;i<sp.length;i++)
        {
            //Check for the array if it matches number
            if(sp[i].matches("(\\d+)"))
                //Adding the numbers
                v+=Integer.parseInt(sp[i]);
            else
            {
                //sorting the characters
                char[] c=sp[i].toCharArray();
                Arrays.sort(c);
                String r=new String(c);
                //Adding the resulting word into list
                ls.add(r);
            }
        }
        //Sorting the resulting words in ascending order
        Collections.sort(ls);
        //Appending the number in the end of the list
        ls.add(v);
        //Displaying the string using Iteartor
        Iterator it=ls.iterator();
        while(it.hasNext())
            System.out.print(it.next()+" ");
        long time=System.currentTimeMillis()-st;
        System.out.println("\n Time Taken:"+time);
    }
}

0 个答案:

没有答案