程序似乎只是读取.txt文件的每隔一行

时间:2014-11-18 05:31:33

标签: java file-io

我正在处理一项任务,我使用扫描程序读取.txt文件的行和标记。我需要进行一些转换并重新排列一些字符串,这是我使用一些辅助方法完成的。问题是代码只适用于从文件中读取的每一行。我想我可能在代码的开头某处乱搞了一些东西。我需要修改的任何提示或提示?这就是我所拥有的:

public static void main(String[] args) throws FileNotFoundException {
    Scanner input = new Scanner(new File("PortlandWeather2013.txt"));
    while (input.hasNextLine()) {
        String header = input.nextLine();
        System.out.println(header);

        Scanner input2 = new Scanner(header);

        while (input2.hasNextLine()){
            String bottomHeader = input.nextLine();
            System.out.println(bottomHeader);

            String dataLines = input.nextLine();

            Scanner linescan = new Scanner(dataLines);

            while (linescan.hasNext()){

                String station = linescan.next();
                System.out.print(station+ " ");

                String wrongdate = linescan.next();
                String year = wrongdate.substring(0,4) ;
                String day = wrongdate.substring(6);
                String month = wrongdate.substring(4,6);

                System.out.print(month + "/" + day + "/" + year);

                double prcp = linescan.nextDouble();
                System.out.print("\t  "+prcpConvert(prcp));

                double snwd = linescan.nextDouble();
                System.out.print("\t  " + snowConvert(snwd));

                double snow = linescan.nextDouble();
                System.out.print("\t" + snowConvert(snow));

                double tmax = linescan.nextDouble();
                System.out.print("\t" + tempConvert(tmax));

                double tmin = linescan.nextDouble();
                System.out.println("\t" + tempConvert(tmin));


            }

        }
    }
}

public static double prcpConvert(double x){

    double MM = x/1000;
    double In = MM * 0.039370;
    double rounded = Math.round(In * 10)/10;
    return rounded;


}
public static double snowConvert(double x){
    double In = x * 0.039370;
    double rounded = Math.round(In * 10)/10;

    return rounded;
}

public static double tempConvert(double x){
    double celsius = x/10;
    double fahrenheit = (celsius *9/5)+32;
    double rounded = Math.round(fahrenheit *10)/10;

    return rounded;
}

1 个答案:

答案 0 :(得分:0)

nextLine()并不只是获取最后一行,它也会前进一行。在你的第二个循环之前,你正在调用nextLine()两次,导致你在循环的每次迭代中前进两行。

您可以通过设置dataLines = bottomHeader而不是再次调用nextLine()来解决问题。