未从文件中正确读取值

时间:2012-12-06 05:03:20

标签: java arrays arraylist file-io

我正在尝试从用逗号分隔的文件中读取x,y坐标。但是,元素未正确添加到ArrayList。我在哪里错了?

ArrayList<Double> xpointArrayList = new ArrayList<Double>();
ArrayList<Double> ypointArrayList = new ArrayList<Double>();
try {
    BufferedReader input = new BufferedReader(new FileReader(args[0]));
    String line;
    while ((line = input.readLine()) != null) {
        line = input.readLine();
        String[] splitLine = line.split(",");

        double xValue = Double.parseDouble(splitLine[0]);
        double yValue = Double.parseDouble(splitLine[1]);

        xpointArrayList.add(xValue);
        ypointArrayList.add(yValue);
    }
    input.close();

    } catch (IOException e) {

    } catch (NullPointerException npe) {

    }

    double[] xpoints = new double[xpointArrayList.size()];
    for (int i = 0; i < xpoints.length; i++) {
        xpoints[i] = xpointArrayList.get(i);
    }
    double[] ypoints = new double[ypointArrayList.size()];
    for (int i = 0; i < ypoints.length; i++) {
        ypoints[i] = ypointArrayList.get(i);
    }

当我在xpoints和ypoints数组上执行Array.toSring调用时。它只有一个数字。例如,在文件中:

1,2
3,4
0,5

xpoints数组只有3.0,ypoints数组只有4.0。哪里出错了?

3 个答案:

答案 0 :(得分:6)

while ((line = input.readLine()) != null) {
    line = input.readLine();

你只需读一行,丢弃它,然后再读一行。

冲洗,重复(因为它是一个循环)。

将来,你真的应该考虑使用调试器。您可以在执行代码时逐步执行代码,并准确查看正在进行的操作。学习使用它将是无价的

编辑添加:由于GregHaskins指出了以下评论,您还通过捕获NullPointerException并且不对其进行操作来模糊问题。在循环的第二次迭代中,line在第二次调用null时将为readLine(),因为文件中没有任何内容。对split()的调用然后会抛出一个NullPointerException,你会抓住......然后默默地忽略。

答案 1 :(得分:1)

您还可以使用Scanner类读取输入。以下是使用Scanner和File类读取文件的代码的修改版本:

ArrayList<Double> xpointArrayList = new ArrayList<Double>();
ArrayList<Double> ypointArrayList = new ArrayList<Double>();
try {
    Scanner input = new Scanner(new File("testing.txt"));
    String line;
    while (input.hasNextLine()) {
        line = input.nextLine();
        String[] splitLine = line.split(",");

        double xValue = Double.parseDouble(splitLine[0]);
        double yValue = Double.parseDouble(splitLine[1]);

        xpointArrayList.add(xValue);
        ypointArrayList.add(yValue);
    }
    input.close();

    } catch (IOException e) {

    } catch (NullPointerException npe) {

    }

    double[] xpoints = new double[xpointArrayList.size()];
    for (int i = 0; i < xpoints.length; i++) {
        xpoints[i] = xpointArrayList.get(i);
    }
    double[] ypoints = new double[ypointArrayList.size()];
    for (int i = 0; i < ypoints.length; i++) {
        ypoints[i] = ypointArrayList.get(i);
    }

答案 2 :(得分:1)

你的阅读风格不对。您正在调用readLine()两次。一个在顶部,另一个在进入while()循环之后。这样你就不会处理所有的点。某些点坐标会被忽略。 你应该使用。

while ((line = input.readLine()) != null) {

//line = input.readLine(); */Remove this */

*/your code */

}
相关问题