【问题标题】:Separating lines in a file by even and odd numbers用偶数和奇数分隔文件中的行
【发布时间】:2013-02-02 04:21:34
【问题描述】:

我有一个文件设置如下:

10   10
12   32
38   12

我需要将偶数槽中的线放在一个数组中,将奇数槽中的线放在另一个数组中。我是java新手,我不知道该怎么做。我已经在互联网上搜索了几个小时,但没有找到任何东西。请帮我!我会很感激的!

我正在使用缓冲读取器读取文件。我已经编写了一个程序,它读取文件并将所有行放在一个数组中,现在我只需要知道如何编写代码来分隔行。所以第 1,3,5,7,9 行将在一个数组中,第 2,4,6,8 行将在另一个数组中。

我将它们放在一个数组中的代码:

 private static final String FILE = "file.txt";
    private static Point[] points;


    public static void main(final String[] args){
        try{
            final BufferedReader br = new BufferedReader(new FileReader(new File(FILE)));
            points = new Point[Integer.parseInt(br.readLine())];
            int i = 0;
            int xMax = 0;
            int yMax = 0;
            while(br.ready()){
                final String[] split = br.readLine().split("\t");
                final int x = Integer.parseInt(split[0]);
                final int y = Integer.parseInt(split[1]);
                xMax = Math.max(x, xMax);
                yMax = Math.max(y, yMax);
                points[i++] = new Point(x, y);




            }

【问题讨论】:

  • 您能分享一下您现在拥有的用于读取它的代码的 sn-p 吗?也许可以声明您想要拆分的两个变量?那么很容易向您展示如何获得最后一点......
  • 你可以逐行阅读。
  • 如果你有一个包含“所有行”的数组,你可以做一个循环:if (lineNumber % 2 == 0) ...
  • 好的,我已经发布了代码。还有弗洛里斯,这是一个想法。我想知道它是否能够在我已经相当容易的代码中实现......

标签: java arrays file-io bufferedreader


【解决方案1】:

试试

    List<String> list1 = new ArrayList<>();
    List<String> list2 = new ArrayList<>();
    String line;
    for (int i = 0; (line = br.readLine()) != null; i++) {
        if (i % 2 == 0) {
            list1.add(line);
        } else {
            list2.add(line);
        }
    }
    String[] even = list1.toArray(new String[list1.size()]);
    String[] odd = list2.toArray(new String[list2.size()]);

【讨论】:

  • 是的 +1,因为这允许可变长度的文件。没想到。计数变量也更加优雅。
【解决方案2】:
String[] even = new String[100];
String[] odd = new String[100];
int counter = 0;
String text;

while(text=readLine() != null) {
    if(counter%2 == 0) {
         even[counter/2] = text;
    } else {
         odd[(counter-1)/2] = text;
    }

     counter++;
}

您需要根据文件的行数调整数组的大小。

代码做什么:循环不断读取行。如果 counter 是偶数,则 counter%2 == 0 为真。如果 counter 是偶数,则 counter/2 将是一个没有余数的整数,因此不会丢失任何内容。如果 counter 是奇数,则 (counter-1)/2 也是如此。

【讨论】:

  • 是的......这是我在评论中开始的循环的其余部分。 (+1)。
  • 干杯!想一点代码可以在这里做更多的解释。
  • 有趣...我喜欢它..让我尝试一些东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-06
  • 1970-01-01
  • 2014-08-31
相关资源
最近更新 更多