【问题标题】:Program skips everyother line, but not sure why [duplicate]程序跳过每隔一行,但不知道为什么[重复]
【发布时间】:2012-09-27 01:10:51
【问题描述】:

我的程序打印该行上的所有数据,但每隔一行打印一次。我知道它与“nextLine”有关,但我找不到导致问题的原因。

import java.io.*;
import java.util.*;

public class hw2
{
    public static void main (String[] args) throws Exception
    {

    String carrier;
    int flights;
    int lateflights;
    int ratio;

    String[][] flightData= new String [221][3];
    String[] temp;

    File file = new File ("delayed.csv");
    Scanner csvScan = new Scanner(file);

    int c = 0;
        while ((csvScan.nextLine()) != null){

        String s = csvScan.nextLine();

        temp = s.split(",");

        for(int i =0; i < temp.length ; i++)
            System.out.println(temp[i]);

        flightData[c][0] = temp[1];
        flightData[c][1] = temp[6];
        flightData[c][2] = temp[7];
        c = c+1;
        }

    }

}

【问题讨论】:

    标签: java arrays lines skip


    【解决方案1】:

    考虑这种方法(参见doc here):

    Scanner csvScan = new Scanner(file);
    while (csvScan.hasNextLine()) {
        String s = csvScan.nextLine();
        // for testing
        System.out.println(s);
        // ... rest of code
    }
    

    【讨论】:

    • Facepalm Ofc。 +1 这是正确的答案。
    • 是的,您在 while 循环中的测试实际上从扫描仪中删除了一行。你把它改成hasNextLine(),你就不会跳行了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    相关资源
    最近更新 更多