Why is an exception thrown on parsing data from the first string array but not when skipping the first array?

huangapple go评论73阅读模式
英文:

Why is an exception thrown on parsing data from the first string array but not when skipping the first array?

问题

在我的系统中,我有一个同时读取 CSV 文件的 Excel 阅读器。

这是我读取 CSV 文件的方式:

Path path = Paths.get(this.getFilePath());
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();

try(BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8);
    CSVReader reader = new CSVReaderBuilder(br).withCSVParser(parser).build()) {

    rows = reader.readAll();
}

这有效地从 CSV 文件读取数据。CSV 文件中的数据存储在一个字符串数组的列表中。

现在我注意到从列表中读取数据时有一些我不明白的情况。

以下是我从列表中读取数据的方式:

if (rows != null && rows.size() > 1) {
    for (String[] row : rows) {
        int i = Integer.parseInt(row[0]);
        String name = row[1];
        double d = Double.parseDouble(row[2].replace(",", "."));
    }
}

如果从列表中获取第一个数组,并尝试将数组中的第一个字符串从 String 类型解析为 int 类型时,会抛出 java.lang.NumberFormatException: For input string: " 27" 错误。

但是,如果跳过第一个数组(即 Excel 行):

if (rows != null && rows.size() > 1) {
    for (int i = 1; i < rows.size(); i++) {  //i = 1,跳过第一个数组(Excel 行)
        String[] row = rows.get(i);
        
        int num = Integer.parseInt(row[0]);
        String name = row[1];
        double d = Double.parseDouble(row[2].replace(",", "."));
    }
}

这种方式就不会抛出 java.lang.NumberFormatException 错误。

我不理解为什么在不跳过第一个数组(Excel 行)的情况下会抛出 java.lang.NumberFormatException 错误。

我需要保留 Excel 文件中的第一行,不能跳过它。这是否与读取 Excel 文件有关?与我使用的阅读器有关吗?

是否有人遇到过这个问题或者能给我提供帮助?

英文:

In my system I have an Excel reader that also reads csv files.

This is the way I read the csv file:

		Path path = Paths.get(this.getFilePath());
		CSVParser parser = new CSVParserBuilder().withSeparator(&#39;;&#39;).build();

		try(BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8);
		    CSVReader reader = new CSVReaderBuilder(br).withCSVParser(parser).build()) {

			rows = reader.readAll();

This works.
The data from the csv file is stored in a list of string arrays.

Now I noticed something when reading the data from the list which I don't understand.

This is the way I read the data from the list:

if (rows != null &amp;&amp; rows.size() &gt; 1) {
			for (String[] row : rows) {
									
				int i = Integer.parseInt(row[0]);
				String name = row[1];
				double d = Double.parseDouble(row[2].replace(&quot;,&quot;, &quot;.&quot;));

			}
		}

If the first array is fetched from the list and the first string from the array is parsed from String to int, java.lang.NumberFormatException: For input string: " 27" is thrown.

But if the first array (first excel line) is skipped:

			if (rows != null &amp;&amp; rows.size() &gt; 1) {
			for (int i = 1; i &lt; rows.size(); i++) {  //i = 1, skipp first array(excel line)
				String[] row = rows.get(i);

				int i = Integer.parseInt(row[0]);
				String name = row[1];
				double d = Double.parseDouble(row[2].replace(&quot;,&quot;, &quot;.&quot;));

			}
		}

This way no java.lang.NumberFormatException: For input string: is thrown.

I do not understand why a java.lang.NumberFormatException is thrown if the first array (excel line) is not skipped.

The first line from the excel file is needed and should not be skipped. Can it have something to do with reading the excel file? With the reader I use?

Does anyone know this problem or can anyone help me?

答案1

得分: 2

因为你的数字前面有一个前导空格,所以会出现这些错误。你可以在解析数字之前使用 trim 函数。这样可以去除空格并消除解析错误。

if (rows != null && rows.size() > 1) {
    for (int i = 1; i < rows.size(); i++) {  //i = 1,跳过第一行(Excel 行)
        String[] row = rows.get(i);

        int num = Integer.parseInt(row[0].trim());
        String name = row[1];
        double d = Double.parseDouble(row[2].replace(",", "."));

    }
}

你还可以尝试:

Integer.parseInt(row[0].replaceAll("\\D+", ""));

这会从字符串中移除所有非数字字符。

英文:

You get these error, because your number has a leading blank. You can use trim before parsing the number. These should remove the blank(s) and the parse error.

        if (rows != null &amp;&amp; rows.size() &gt; 1) {
        for (int i = 1; i &lt; rows.size(); i++) {  //i = 1, skipp first array(excel line)
            String[] row = rows.get(i);

            int i = Integer.parseInt(row[0].trim());
            String name = row[1];
            double d = Double.parseDouble(row[2].replace(&quot;,&quot;, &quot;.&quot;));

        }
    }

You can also try:

Integer.parseInt(row[0].replaceAll(&quot;\\D+&quot;, &quot;&quot;));

This removes allnon Digits from the String.

答案2

得分: 1

以下是翻译好的内容:

尝试解析的字符串有一个前导空格:" 27"。这就是导致错误的原因。以下代码也会抛出异常:

public class MyClass {
    public static void main(String args[]) {
      int i = Integer.parseInt(" 27");
      System.out.println(i);
    }
}

作为一般规则,在解析之前应该对输入进行清理。例如,如果它将是一个数字值,将字符串传递给 parseInt() 之前进行 trim() 处理。

英文:

The string it's trying to parse has a leading space: " 27". That is what's causing the error. The following code also throws the exception:

public class MyClass {
    public static void main(String args[]) {
      int i = Integer.parseInt(&quot; 27&quot;);
      System.out.println(i);
    }
}

As a general rule you should sanitize your input before parsing it. For example, if it's going to be a numeric value, trim() the string before feeding it to parseInt().

答案3

得分: 1

你的解析不够充分。你得到的错误显示一个单元格包含一个带有前导空格的数字。

> java.lang.NumberFormatException: 对于输入字符串:" 27"

你在这个单元格值上调用了Integer.parseInt()。根据它的文档,parseInt() 拒绝前导空格。

在调用parseInt之前,你需要修剪(trim)该值。参见String.trim()。

英文:

Your parsing is not adequate. The error you get shows that one cell contains a number with a leading space.

> java.lang.NumberFormatException: For input string: " 27"

You call Integer.parseInt() on this cell value. By its documentation, parseInt() rejects leading spaces.

You will need to trim the value before calling parseInt. See String.trim().

huangapple
  • 本文由 发表于 2020年8月21日 21:04:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63523456.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定