还有另一个文本文件进入Arraylist

时间:2011-04-18 19:33:22

标签: java text arraylist

我正在尝试在文本文件中的每一行上获取每个元素,以便我可以逐行执行计算。问题是我只能从我的文本中获取每个单独的元素。我希望能够指向第50行并提取第一个元素,第二个元素,第三个元素 - 然后转到第51行并执行相同操作。

    import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ReadWithScanner {



    public static void main(String[] args) throws IOException {
            Scanner scanner = new Scanner(new File("/Users/evanlivingston/2.txt"));
            List<Double> doubles = new ArrayList<Double>();{
            while(scanner.hasNextLine()){
                doubles.add(scanner.nextDouble());
            }
            for( int counter=0; counter<doubles.size(); counter++ ) {
                // j=i+1 to calculate the distance between two points only once, 
                // not one way and back; also skip calculating distance between 
                // the same point
                for( int j=counter+1; j<doubles.size(); j++ ) { 
                    Double c1 = doubles.get(counter);
                    Double c2 = doubles.get(j); 
            System.out.println(c1 - c2);    
                }
            }
        }
    }
    }

我的文字文件如下:

0 10 12 4 5 6

0 10 12 4 5 7

... 20 20 20 20 20 20

2 个答案:

答案 0 :(得分:3)

我认为问题在于:

while(scanner.hasNextLine()){
            doubles.add(scanner.nextDouble());
        }

如果您的意图是解析一行中的每个double并且有多行,那么您做错了。 我认为你需要这样的东西:

while (scanner.hasNextLine()){
      String currentLine = scanner.nextLine();
      //here iterate the string currentLine to get each double
}

答案 1 :(得分:1)

扩展0verbose的答案:看起来你想逐行获取元素,即稍后你想知道双线是哪一行。

因此,尝试使用List<List<Double>>并创建一个子列表,其中包含每行的双精度数。 如果所有行都具有相同数量的元素,则可以使用单个列表,然后使用index = line_no * num_elements_per_line + element_index_in_line来处理特定元素。