运算符“!=”不能应用于双精度浮点数,空值。

3

我在下面的代码中遇到了一个错误:

  HashMap map = new HashMap();
  map.put("driver", userId);
  map.put("customer", customerId);
  map.put("rating", 0);
  map.put("timestamp", getCurrentTimestamp());
  map.put("destination", destination);
  map.put("location/from/lat", pickupLatLng.latitude);
  map.put("location/from/lng", pickupLatLng.longitude);
  map.put("location/to/lat", destinationLatLng.latitude);
  map.put("location/to/lng", destinationLatLng.longitude);
  map.put("distance", rideDistance);
  historyRef.child(requestId).updateChildren(map);

他们建议添加以下内容:

在创建哈希映射之前或对于每个纬度和经度,执行if(pickupLatLng.latitude != null && pickupLatLng.longitude != null && destinationLatLng.latitude != null && destinationLatLng.longitude != null)

但是当我尝试这样做时,我遇到了以下错误:运算符!=不能应用于double、null

有人能帮助我吗?


2
double 是一种原始类型,因此您无法检查其是否为 null。相反,您可以检查它是否为 0 或更低的值。 - Darwind
1
由于double是一个原始类型而不是对象,因此您无法将其与null进行比较。请将其与数字(零)进行比较。请参见此处 - Jon Goodwin
这个可能会有用 https://dev59.com/a2ox5IYBdhLWcg3wnViy - Rohit5k2
请分享NPE日志!我猜纬度或经度没问题。 - Radesh
3个回答

5

double是一种原始类型,它不能为null。相反,您可以使用Double,然后将其与null进行比较。


1
我猜纬度或经度都可以,你的pickupLatLng或destinationLatLng为空并导致了NPE错误,因此我认为你应该使用这段代码。
if (pickupLatLng != null && destinationLatLng != null) {}

-1
首先,Java中的double类型不能为null,也不能与Java中的null进行比较。(double类型是一种原始(非引用)类型,原始类型不能为null。)
尝试这个,
if( pickupLatLng.latitude != 0 && pickupLatLng.longitude != 0 && destinationLatLng.latitude != 0 && destinationLatLng.longitude != 0) 

这并没有解释为什么 OP 会出现这个错误,所以答案一点也不有用。请重新表述你的回答或者删除它。 - Darwind

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接