java.lang.NullPointerException读取csv文件[重复]时发生异常

问题描述 投票:0回答:1

我正在尝试使用距离矩阵API计算起点和终点之间的距离和旅行时间。

我使用了以下代码:

 public class read_csv_file {
 public static ArrayList<String> getTownList(String fileName) {
    try {
        ArrayList<String> towns = new ArrayList<String>();
        File csvFile = new File(fileName);
        BufferedReader br = new BufferedReader(new FileReader(csvFile));
        String line = "";
        while ((line = br.readLine()) != null) {
            String[] arr = line.split(",");
            towns.add(arr[0]);
        }
        return towns;
    } catch (IOException ex) {
        ex.printStackTrace();
        System.out.println("Failed: could not find file.");
    }
    return null;
}
public static String getTown(ArrayList<String> towns) {
    int townsLen = towns.size();
    int rand = (int) (Math.random() * townsLen + 1);
    return towns.get(rand);
}
public static long getDriveDist(String origins, String destination) throws ApiException, InterruptedException, IOException {
    GeoApiContext distCalcer = new GeoApiContext.Builder()
            .apiKey("key")
            .build();
    DistanceMatrixApiRequest req = DistanceMatrixApi.newRequest(distCalcer);
    DistanceMatrix result = req.origins(origins)
            .destinations(destination)
            .mode(TravelMode.DRIVING)
            .avoid(DirectionsApi.RouteRestriction.TOLLS)
            .language("en-US")
            .await();
   long dist = result.rows[0].elements[0].distance.inMeters;
  return dist;
}
public static void main(String[] args) throws ApiException, InterruptedException, IOException {

    ArrayList<String> towns = getTownList("src/main/java/test_three.csv");

    if (towns != null) {
        // get 2 specific towns from the file
        // remove the first from ArrayList before getting the second
        String town1 = getTown(towns);
        towns.remove(towns.indexOf(town1));
        String town2 = getTown(towns);

        long dist = getDriveDist(town1, town2);

        // totalMinutes is based on walking at a speed of 10.6 minutes per km
        long totalMinutes = (long) (((dist / 1000) * 10.6));

        // calculate the days, hours and minutes from total minutes
        int days = (int) (totalMinutes / 24 / 60);
        int hours = (int) (totalMinutes / 60 % 24 );
        int minutes = (int) (totalMinutes / 60);

        // print
        System.out.println("It will take" + days + "days" + hours + "hours and" + minutes + "minutesto walk from"
                + town1 + "to"
                + town2 + ".");

    } else {
        System.out.println("Failed: null ArrayList for towns");
    }
   }}

但是抛出:

Exception in thread "main" java.lang.NullPointerException
at line  "long dist = result.rows[0].elements[0].distance.inMeters;")

我的csv文件的示例:

Rochdale,Greater Manchester,North West
Lowestoft,Suffolk,South East
Kingston-upon-Thames,Greater London,London
Horley,Surrey,South East

我进行了一些研究,发现原因是我试图访问一个不存在的表单元格,例如表[4],而表的大小为4,但是我在这里看不到问题出在哪里。如果您有任何想法,请帮助我

谢谢。

java csv google-distancematrix-api
1个回答
0
投票

没有足够的信息来完全确定,但是我怀疑您的问题出在线路上:

long dist = result.rows[0].elements[0].distance.inMeters

我建议检查该链中的每个变量,以查看是否确实存在值:

if (null != result) {
  if (null != result.rows[0]) {
    if (null != result.rows[0].elements[0]) {
       // ... etc.  ...
    } else {
      System.out.println("ELEMENTS is null");
      return -1;
  } else {
    System.out.println("ROWS is null");
    return -1;
} else {
  System.out.println("RESULT is null");
  return -1;
}
© www.soinside.com 2019 - 2024. All rights reserved.