1

编写一个 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);
    }
}
4

0 回答 0