【问题标题】:turning .CSV numeric string values into an integer. java将 .CSV 数字字符串值转换为整数。爪哇
【发布时间】:2022-01-10 00:52:23
【问题描述】:

我正在尝试从 CSV 文件中获取 3 个 int 值并将它们加载到我可以在二次函数中使用的变量中。我遇到的问题是,当我从 CSV 中获取值时,它们被视为字符串。我试过使用 Integer.parseInt(variable);和 Double.parseDouble(variable);。我已经尝试使用 variable.getClass() 和 prints 进行故障排除,但我不断得到,我不知所措

我的代码如下:

public static void main(String[] args) {
        String pathFile = "/Users/stephen/QuadData3.csv";
        String line = "";

        try {
            BufferedReader br = new BufferedReader(new FileReader(pathFile));
            while ((line = br.readLine()) != null) {
                String[] values = line.split(",");

                int a = Integer.parseInt(values[0]);
                int b = Integer.parseInt(values[1]);
                int c = Integer.parseInt(values[2]);

                System.out.println(a);
                System.out.println(b);
                System.out.println(c);


            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        }
    }
}

我明白了 Exception in thread "main" java.lang.NumberFormatException: For input string: "4"

任何帮助将不胜感激

【问题讨论】:

  • 您可能正在尝试将非整数转换为整数。
  • 该代码对我来说很好用。可能问题出在你的 CSV 格式上,你能分享一下吗?

标签: java string csv type-conversion integer


【解决方案1】:

CSV文件中的列/字段很可能使用了双引号",在拆分或解析整数值之前需要将其去掉:

String[] values = line.replaceAll("\"", "").split(","); // values won't have "

String[] values = line.split(",");
int a = Integer.parseInt(values[0].replaceAll("\"", ""));
// etc...

【讨论】:

    【解决方案2】:

    最好使用 CSV 库来读取 CSV 文件。 SuperCSV 是一个不错的选择。请参考以下链接http://super-csv.github.io/super-csv/index.html

    【讨论】:

      【解决方案3】:

      也可以是 '.csv' 行中的一些不可打印字符

      尝试添加此过滤器以将其全部删除:

      int a = Integer.parseInt(values[0].replaceAll("\\P{Print}", ""));
      

      【讨论】:

        猜你喜欢
        • 2021-08-19
        • 1970-01-01
        • 1970-01-01
        • 2019-01-10
        • 2011-06-24
        • 2013-08-25
        • 1970-01-01
        • 2016-07-02
        相关资源
        最近更新 更多