2012-03-24 61 views
1

我正在为读取CSV文件的类创建程序,并对文件中给出的数据执行各种数学公式。 CSV文件是在设置:虽然文件读取器的循环麻烦?

  • longitude1,latitude1,timeStamp1
  • longitude2,latitude2,timeStamp2
  • longitude3,latitude3,timeStamp3

(并继续对约100个不同的坐标)。

现在我专注于经度值---我很难让我的while循环执行我也需要的操作。我需要能够让程序从经度1减去经度2(其中lon1和lon2在我们经过循环时最终要经过每个坐标)。

我遇到的问题是循环没有创建'重叠'(缺少更好的术语)。它在前两个坐标上执行数学运算,然后跳到下两个数据...从而跳过其他所有操作。

[即:在循环中执行:lon2 - lon1和lon4-lon3但跳过lon3-lon2]

我有我的问题在于我,而循环的开始预感,但我真的穿上”不知道如何解决它。我会喜欢一些帮助。 以下是我目前的代码:

import java.io.*; 
import java.util.*; 
public class SearchAndR { 
    public static void main(String[] args) throws FileNotFoundException { 
     // creates a Scanner called "keyboard" to read in the file name 
     Scanner keyboard = new Scanner(System.in); 
     // prompts user for file name 
     System.out.println("Enter the name of the file you intend to read in"); 
     // Stores file name as a string so that we may read it in 
     String file = keyboard.nextLine(); 
     // creates a new Scanner called fr(short for filereader) so we can read 
     // in the file 
     // then we create a File object using the constructor new with the class 
     // "File" 
     // this takes in our string "file" as a parameter to read it in 
     // reading in our file object to the scanner 
     Scanner fr = new Scanner(new File(file)); 
     // Creating format for hike1.csv file 
     System.out.println("--- Hike Analysis ---"); 
     System.out.println("File: " + file); 
     // Calling HW4 Class to use in the rest of the program 
     HW4Util util = new HW4Util(); 
     // Establishing counting variable for distance for the while loop 
     double totaldistance = 0; 
     while (fr.hasNextLine()) { 
      String line = fr.nextLine(); 
      String[] stamp1 = line.split(","); 
      String line2 = fr.nextLine(); 
      String[] stamp2 = line2.split(","); 
      double lon1 = Double.parseDouble(stamp1[0]); 
      double lat1 = Double.parseDouble(stamp1[1]); 
      String time1 = (stamp1[2]); 
      double lon2 = Double.parseDouble(stamp2[0]); 
      double lat2 = Double.parseDouble(stamp2[1]); 
      String time2 = (stamp2[2]); 
      // This is just to check to see if the overlap is occurring! 
      // This should not be included in the project. 
      System.out.println("this is longitude" +lon1); 
      System.out.println("this is longitude" +lon2); 
      // returns the distance between two coordinates as a fraction of a 
      // mile 
      double dist = util.distance(lat1, lon1, lat2, lon2); 
      totaldistance = totaldistance + dist; 
      totaldistance = (double) (Math.round(totaldistance * 10000))/10000; 
     } 
     System.out.println("Total distance traveled: " + totaldistance + " miles"); 
    } // end method main 
} // end class filereader 

回答

3

这是因为您正在一次循环运行中读取2行。我会建议做这样的事情:

​​

为什么它没有按照你的意图工作?那么,想象一下当前处于文件开始的指针。 使用fr.nextLine(),您正在读取当前指向的行并且指针停止。 在你的循环的一次运行中,你读2连续的行,做你的数学,并在接下来的运行再读2多行