0

我有一个设置如下的文件:

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);




            }
4

2 回答 2

3

尝试

    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()]);
于 2013-02-02T04:32:59.887 回答
1
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 也是如此。

于 2013-02-02T04:25:23.100 回答