我目前遇到的问题是我的CVSParser的IF语句不起作用。国家名称“德国”不存在,可以,但是在发生此错误时字符串notf没有返回,而是得到:
"java.lang.IllegalArgumentException: Mapping for Germany not found, expected one of [Country, Exports, Value (dollars)]".
我假定正在返回的值是一个空值,因为CVSParser返回一个字符串,但是,为countryName分配一个空值并不能使我的代码正常工作。
当我使用测试仪时出现了问题。
我需要采取什么步骤来解决?同样,一般来说,当要查找的方法不存在时,如何确定方法返回的值? (特别是不在文档中时。)
public String countryInfo (CSVParser parser,String country){
FileResource fr = new FileResource();
String exports= "";
String countryName= "";
String value= "";
for (CSVRecord record : parser){
exports=record.get("Exports");
countryName=record.get(country);
value= record.get("Value");
if (exports== null ||countryName!= country){
String notf= "info has not been found";
return notf;
}
}
String info= countryName +":"+ exports;
return info;
}
public void tester (){
FileResource fr = new FileResource();
CSVParser parser = fr.getCSVParser();
countryInfo(parser,"Germany");
}
最佳答案
关于字符串比较的@HovercraftFullOfEels注释是正确的。
但是异常(exception)说
"java.lang.IllegalArgumentException: Mapping for Germany not found, expected one of [Country, Exports, Value (dollars)]"
测试代码会导致通话
countryName=record.get("Germany");
异常表明应该在哪里
countryName=record.get("Country");
因此,如果您需要有关德国导出的信息,则代码应为
public String countryInfo (CSVParser parser,String desiredCountry){
FileResource fr = new FileResource();
String exports= "";
String countryName= "";
String value= "";
for (CSVRecord record : parser){
exports=record.get("Exports");
countryName=record.get("Country");
value= record.get("Value");
if (exports== null || !countryName.equals(desiredCountry)){
String notf= "info has not been found";
return notf;
}
}
String info= countryName +":"+ exports;
return info;
}
public void tester (){
FileResource fr = new FileResource();
CSVParser parser = fr.getCSVParser();
countryInfo(parser,"Germany");
}
关于java - 当csv值不存在时,如何使if语句正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51918614/