2

我正在尝试从文件中读取,当读取空行时,它将在空行之前输出第 22 行。例如,如果程序在第 44 行读取第一个空白行的所有行,那么它将打印第 22 行。

目前我让它工作,以便它读取输入并将其存储到 arrayList 中,然后输出它。我想知道最有效的方法是什么?我还试图确保一次存储的行数不超过 23 行。arraylist 是合适的数据结构吗?

public static void test(BufferedReader r, PrintWriter w) throws IOException {

    ArrayList<String> s = new ArrayList<String>();

    String line;
    int n = 0;
    while ((line = r.readLine()) != null) {
        s.add(line);
        n++;
    }
    Iterator<String> i = s.iterator();
    while (i.hasNext()) {
        w.println(i.next());
    }
}

感谢您的任何建议/意见

4

4 回答 4

1

You can use a simple String[] of size 22 and perform the inserts and the "get" modulo 22.
Your code should looks something like this:

public static void test(BufferedReader r, PrintWriter w) throws IOException {

    String[] prev22 = new String[22];
    String line;
    int n = 0;
    while ((line = r.readLine()) != null) {
        prev22[n % 22] = line;
        if(line.trim() == null){
            w.println(prev22[n-22 % 22]);
        }
        else{
            w.println(line);
        }
        n++;
    }
}
于 2013-09-22T22:38:05.340 回答
1

ArrayList is a bit of an overkill. Since you know exactly the total number of lines you can use a String array.

However, you will have to keep information about what is the current "start pointer" (if you want to keep the order and use it in an effective circular fashion.

Example: Using a custom circular array

 public class CircularStringArray {

    private int currenInsertIndex = 0;

    private String[] array = new String[22];

    public void addString(String element)
    {
        array[currenInsertIndex++] = element;
        currenInsertIndex = currenInsertIndex % array.length;
    }   

    public String printStrings()
    {
        String result = "";
        for(int i=currenInsertIndex; i<array.length; i++)
        result+=i+")"+array[i]+"\n";

        for(int i=0; i<currenInsertIndex; i++)
        result+=i+")"+array[i]+"\n";

        return result;
    }

    public static void main(String args[])
    {
        CircularStringArray test = new CircularStringArray();
        for (int i=0; i<50; i++)
        test.addString(new String(new char[]{(char)i}));

        System.out.println(test.printStrings());            
    }
}
于 2013-09-22T22:39:53.390 回答
0

ArrayList 将存储所有行,直到空白。您可以使用大小为 22 的字符串队列。队列的入队出队操作花费恒定的 O(1) 时间,并且内存使用量也将最小化

于 2013-09-22T22:43:07.257 回答
-1

这应该工作

public static void test(BufferedReader r, PrintWriter w) throws IOException {

   String[] s = new String[22];

   String line;
   int n = 0;
   while ((line = r.readLine()) != null) {
       s[n] = line;
        //This will take n to 0 when n is 21 i.e. last array position
       n = (n+1) % 22;
   }
   int last = n;

   //Will print it in the same order in which those lines were read.
   do{
         w.println(s[n]);
         n = (n+1) % 22;
     } while(n != last);
}
于 2013-09-22T22:48:28.420 回答