This question already has answers here:
What is a NullPointerException, and how do I fix it?

(12个答案)


在27天前关闭。





我正在尝试使用距离矩阵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,但是我在这里看不到问题来自。如果您有任何想法,请帮助我

谢谢。

最佳答案

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

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;
}

关于java - 读取csv文件时出现java.lang.NullPointerException异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61993954/

10-14 02:47