问题描述
我正在尝试读取一个用逗号分隔的值文件,但似乎无法使我的代码正常工作。有什么提示我的代码不正确吗?
注意:尝试仅读取 Price 列,并确保值不为NULL,不适用,小于80和大于130。
SpreadSheet:
boolean flag = true;
File inputF = new File("data.csv")
InputStream getStream = new FileInputStream(inputF);
try{
if(getStream.read() != -1){
BufferedReader reader = new BufferedReader(new InputStreamReader(getStream));
String line;
while((line = reader.readLine()) != null){
String[] csvs = line.split(",");
for (String str : csvs){
if (str != null && (str.equals("NA") || str.length() == 0)) {
System.out.println(str);
flag = false;
break;
}
}
if (!flag){
break;
}else{
String Price = csvs[1];
price = price.trim();
Integer priceValue = new Integer(Price); //exception occurs here
if (priceValue != null && (priceValue < 80 || priceValue > 130)){
flag = true;
}
}
}
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(flag);
return flag;
错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "PRICE"
预期输出:(基于提供的电子表格)
True
解决方法
我正在尝试读取Excel文件...。
代码...和输出...表明您实际上是在尝试解析CSV文件,而不是Excel文件。
异常消息是这样的:
Exception in thread "main" java.lang.NumberFormatException:
For input string: "PRICE"
错误消息正在显示。该“ PRICE”字符串来自CSV文件的第一行。解决方案很简单。读取并丢弃文件的第一行;即包含列名而不是数据的行。
,在“ PRICE”的第一行给出了错误。 仅检查数字:
String price = csvs[1].trim();
if (price.matches("-?\\d+")) { // Possibly negative integer.
int priceValue = Integer.parseInt(Price);
if (priceValue < 80 || priceValue > 130){
flag = true;
}
}