为什么在java中解析csv电子表格会引发numberformatexception?

n6lpvg4x  于 2021-07-05  发布在  Java
关注(0)|答案(2)|浏览(398)

我试图读取逗号分隔的值文件,但我似乎无法让我的代码工作。你知道我的代码哪里不正确吗?
注意:尝试只读取price列,并确保值不为null、不适用、小于80和大于130。
电子表格:

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
guz6ccqo

guz6ccqo1#

我正在读一个excel文件。。。。
密码。。。输出。。。表示您实际上是在尝试解析csv文件,而不是excel文件。
例外消息如下:

Exception in thread "main" java.lang.NumberFormatException:
     For input string: "PRICE"

错误消息说明问题。“price”字符串来自csv文件的第一行。解决办法很简单。读取并丢弃文件的第一行;i、 e.包含列名而不是数据的行。

nc1teljy

nc1teljy2#

“价格”的第一行出现错误。仅检查数字:

String price = csvs[1].trim();
    if (price.matches("-?\\d+")) { // Possibly negative integer.
        int priceValue = Integer.parseInt(Price);
        if (priceValue < 80 || priceValue > 130){
            flag = true;
        }
    }

相关问题