我正在尝试从CSV文件读取数据。一切正常,但是当我尝试读取经度和纬度数据时。它给了我下面的错误信息。
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.yogi.guestlogix/com.example.yogi.guestlogix.MainActivity}: java.lang.NumberFormatException: Invalid double: "EVE"
Caused by: java.lang.NumberFormatException: Invalid double: "EVE"**
MainActivity.java
//Airports data begin
InputStream isss = getResources().openRawResource(R.raw.airports);
BufferedReader readerss = new BufferedReader(
new InputStreamReader(isss, Charset.forName("UTF-8"))
);
String liness = "";
//for airports.csv
try {
readerss.readLine();
while ((liness = readerss.readLine()) != null) {
//split by ',' first
String[] airport = liness.split(",");
//Read the data
AirportsData airdata = new AirportsData();
airdata.setAirportname(airport[0]);
airdata.setAirportcity(airport[1]);
airdata.setAirportcountry(airport[2]);
airdata.setAirportIATAcode(airport[3]);
//airdata.setAirportlang(Double.parseDouble(airport[4]));
//airdata.setAirportlat(Double.parseDouble(airport[5]));
AirportsDatas.add(airdata);
}
} catch (IOException e) {
Log.wtf("My Activity", "Reading data file error " + liness, e);
e.printStackTrace();
}
Log.d("Airline", "name is " + AirportsDatas);
AirportsData.java
public double getAirportlang(double airportlang) {
return airportlang;
}
public void setAirportlang(double airportlang) {
this.airportlang = airportlang;
}
public double getAirportlat( ) {
return airportlat;
}
public void setAirportlat(double airportlat) {
this.airportlat = airportlat;
}
@Override
public String toString() {
return "AirportsData{" +
"airportname='" + airportname + '\'' +
", airportcity='" + airportcity + '\'' +
", airportcountry='" + airportcountry + '\'' +
", airportIATAcode='" + airportIATAcode + '\'' +
", airportlang=" + airportlang +
", airportlat=" + airportlat +
'}';
}
**对于此问题的任何解决方案将不胜感激。...
答案 0 :(得分:1)
CSV文件的问题在于,用户(和其他程序员)几乎可以将所需的内容写入文件。
在您的情况下,有人在CSV单元格中输入了一个非数字,您期望该数字为double
浮点数。 Java正确地抱怨无法将其解析为double
。您有两种方法可以处理此类情况:
A)按合同设计
首先,您可以依靠design by contract解决该问题。您可以使用parseLat
方法:
public Double parseLat(String[] csvRow) {
final String lat= csvRow[4];
assertIsNumeric(lat);
}
private void assertIsNumeric(String lat) {
if(!isNumeric(lat)) {
throw new IllegalArgumentException("Lattitude '" + lat + "' is not numeric");
}
}
有许多实现isNumeric
方法some are discussed here的选项。这仍然会停止执行,但是会向用户提供更清晰的消息。
B)防御性设计
第二种选择是提供一种parseLAttitude
方法,该方法用null
替换非数值:
public Double parseLattitude(String[] csvRow) {
final String lattitude = csvRow[4];
if(!isNumeric(lattitude)) {
System.out.println("Could not parse lattitude '" + lat + "'");
return null;
}
return Double.parseDouble(lat);
}
答案 1 :(得分:0)
我认为问题在于,airport [4]和airport [5]可能不是机场的长期和长期。如果这些字段包含字母字符[a-z],则将获得numberFormatException。您可以在打印机场时添加输出吗?
System.out.println(Arrays.asList(airport));
对这个问题?比我们将能够更好地为您提供帮助