【问题标题】:Reading the whole file and then outputting the lines with a certain order读取整个文件,然后按一定顺序输出行
【发布时间】:2016-09-17 07:11:11
【问题描述】:

我正在开发一个函数,它读取一个包含 n 行字符串的文件。

想象文件中的每一行都有编号,从 0 开始。我试图修改这个函数,让它读取整个文件,然后输出编号为 0、3、6、...

接下来是编号为 1、4、7、.... 的行,最后是编号为 2、5、8、.... 的行

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

    String s;

    List<String> tmp = new ArrayList<String>();

    while((s = r.readLine())!=null){
        tmp.add(s);
    }


    for (String text : s) {
        w.println(text);
    }
}

例如:

0
1
2
3
4
5
6
7
8
9

应该输出

0
3
6
9
1
4
7
2
5
8

我确定我需要使用 % 符号。但我似乎无法弄清楚如何。任何帮助将不胜感激

【问题讨论】:

  • 这里的蛮力选项是读取整个文件,每行作为数组中的一个条目,然后遍历这个数组。

标签: java string bufferedreader


【解决方案1】:

如果您仅存储 int 值(使用 Integer.parseInt(s) 并捕获 NumberFormatException),则应使用 List&lt;Integer&gt;

然后您必须像这样对您的列表(使用Collections.sort())进行排序:

    Collections.sort(tmp, new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return new Integer(o1 % 3).compareTo(new Integer(o2 % 3));
        }
    });

【讨论】:

    【解决方案2】:

    创建列表后,您可以使用此循环来实现您想要的:

        int gap = 3;
        for (int i = 0; i < gap; i++) {
            for (int j = i; j < tmp.size(); j+=gap) {
                System.out.println(tmp.get(j));
            }
        }
    

    如果你想跳超过3,你只需更新变量gap。

    【讨论】:

      【解决方案3】:

      对于这个例子,将考虑到它的所有行都在一个字符串数组中,这里我提出了一个递归函数,它在循环中迭代三个

      static int cont=0;
      public static int ReadLines(String[]array,int init)
      {
        if(cont>array.length-1)return 0;
        else
        {
          for (int i = init; i < array.length; i+=3) {
                System.out.println(array[i]);
                cont++;
            }
          return ReadLines(array, init+1);
        }
      }
      

      调用函数

      String[] array = new String[]{"0","1","2","3","4","5","6","7","8","9"};
      ReadLines(array,0);
      

      【讨论】:

        【解决方案4】:

        将文件解析为 3 个列表,然后将一个列表一个接一个地写入输出:

        final int num = 3;
        ArrayList<String>[] lists = new ArrayList[num];
        for (int i = 0; i < num; i++) {
            lists[i] = new ArrayList<>();
        }
        
        String s;
        for (int i = 0; (s = r.readLine())!=null; i++) {
            lists[i % num].add(s);
        }
        
        for (int i = 0; i < num; i++) {
            for (String line : lists[i]) {
                w.println(line);
            }
        }
        

        【讨论】:

          【解决方案5】:

          将行添加到数组或列表中,您可以通过索引获取它们

          【讨论】:

          • 已经是这样了。 tmpList,文件的行被添加到其中。您所说的索引请参见this 答案。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-11
          • 1970-01-01
          • 2010-09-14
          • 1970-01-01
          相关资源
          最近更新 更多