读取 CSV 并将字符串转换为双精度

Read CSV and convert string to double

我是 Java 的新手,我正在使用打开的 CSV 读取一个 csv 文件,我的代码如下:

import java.io.FileReader;
import java.util.Arrays;

import au.com.bytecode.opencsv.CSVReader;

public class ParseCSVLineByLine
{
   double arr []=new arr[10];
   public static void main(String[] args) throws Exception
   {
      //Build reader instance
      //Read data.csv
      //Default seperator is comma
      //Default quote character is double quote
      //Start reading from line number 2 (line numbers start from zero)
      CSVReader reader = new CSVReader(new FileReader("data.csv"), ',' , '"' , 1);

      //Read CSV line by line and use the string array as you want
      String[] nextLine;
      int i=0;
      while ((nextLine = reader.readNext()) != null) {
         if (nextLine != null && i<10) {
            //Verifying the read data here
            arr[i]=Double.parseDouble(Arrays.toString(nextLine).toString());
            System.out.println(arr[i]);
         }
        i++;
       }
   }
}

但是当我只打印

时,这不会 works.But
Arrays.toString(nextLine).toString()

这会打印

[1]
[2]
[3]
.
.
.
.
[10]

我认为转换得到了 problem.Any 的帮助,我们表示赞赏。

事情是:

"[1]"

不是可以解析为数字的字符串!

你的问题是你把数组作为一个整体变成了一个字符串。

所以不用打电话

Arrays.toString(nextLine).toString()

迭代 nextLine 并将每个数组成员交给 parseDouble()!

此外:我很确定您收到了 NumberFormatException 或类似的东西。 JVM 已经告诉您您正在尝试将无效字符串转换为数字。您必须学会阅读 那些异常消息并理解 它们的含义!

长话短说:您的代码可能想要解析“[1]”,但您应该让它解析“1”!