1

I am new to Java and I am reading a csv file using open CSV and my code is below:

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++; } } } 

But this does not works.But when I only print

Arrays.toString(nextLine).toString() 

This prints

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

I think the conversion is having the problem.Any help is appreciated.

3
  • what is input in csv file ? Commented Jan 10, 2017 at 13:41
  • Arrays.toString(nextLine) will most likely result in something that isn't parseable as a double, since even with only one element you'll get the strings you posted, i.e. "[1]". Why not just Double.parseDouble(nextLine[index]) where index is probably 0? Commented Jan 10, 2017 at 13:44
  • Thanks for the accept, I am glad my answer was helpful Commented Jan 11, 2017 at 4:04

1 Answer 1

1

Thing is:

"[1]"

is not a string that could be parsed as number!

Your problem is that you turn the array as a whole into one string.

So instead of calling

Arrays.toString(nextLine).toString() 

iterate nextLine and give each array member to parseDouble()!

Besides: I am pretty sure you receive a NumberFormatException or something alike. The JVM already tells you that you are trying to convert an invalid string into a number. You have to learn to read those exception messages and understand what they mean!

Long story short: your code probably wants to parse "[1]", but you should have it parse "1" instead!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.