解析csv(Java)时如何重新格式化int

时间:2015-06-09 22:49:31

标签: java parsing csv

尝试解析列的容量。在csv文件中,我编辑的数字为30000而不是30,000。在解析文件时,我仍然得到输出为30,000。如何摆脱0两个零之间的空格和逗号?

我收到错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""30"
at     java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)

代码:

      while((line = br.readLine()) != null)
      {
           String[] b = line.split(splitBy);
           String university = "%"+b[3]+"%";

           preparedStatement = connect
                  .prepareStatement("SELECT id FROM usale.university WHERE title LIKE ?");
                   preparedStatement.setString(1, university);


              resultSet = preparedStatement.executeQuery();
              if(resultSet.next())
              {
              universityid = resultSet.getInt("id");
              }
               System.out.println(b[0]+", "+b[1]+", "+b[2]+", "+b[3]+", "+b[4]+", "+b[5]+", "+universityid);

               if(universityid != 0)
               {
                   preparedStatement = connect
                              .prepareStatement("insert into usale.stadium(stadium_id, stadium_name, seat_availability, stadium_capacity, university_id, stadium_city) "
                                    + "values(?,?,?,?,?,?);");
                          preparedStatement.setInt(1, Integer.parseInt(b[0]));
                          preparedStatement.setString(2, b[1]);
                          preparedStatement.setString(3, "all-seater");
                          preparedStatement.setInt(4, Integer.parseInt(b[4]));
                          preparedStatement.setInt(5, universityid);
                          preparedStatement.setString(6, b[2]);
                          preparedStatement.executeUpdate();
               }


            universityid = 0;
      }

编辑(这是一些示例csv数据):

1,Aggie Memorial Stadium,Las Cruces,New Mexico State,“30343”,全座位,

2,Alamodome,圣安东尼奥,UTSA,“65000”,全座位,

3,Albertsons体育场,博伊西,博伊西州,“37000”,全座位,

2 个答案:

答案 0 :(得分:0)

根据您的异常跟踪,您的整数包含双引号。

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

您可以使用以下方法删除它们:

yourString = yourString.replaceAll("\"", "");

万一有额外的空间,我无法看到,但你在问题中提到过。要删除尾随空格,您还可以添加修剪:

yourString = yourString.replaceAll("\"", "").trim();

答案 1 :(得分:0)

如果你的目标是删除逗号和空格,你可以使用replaceAll,而numberString.replaceAll("[, ]", ""); 依次使用正则表达式来删除逗号:

numberString.replaceAll("[,\\s]", "");

30,000

或者,在您的情况下,getCurrencyInstance()代表某种货币或交易。 NumberFormat ' Number number = NumberFormat.getCurrencyInstance().parse(numberString); numberString = number.toString(); 可能会派上用场:

{{1}}