Home > OS >  turning .CSV numeric string values into an integer. java
turning .CSV numeric string values into an integer. java

Time:12-04

I'm trying to grab 3 int values from a CSV file and load them into a variable that I can use in a quadratic function. what I'm having trouble with is that when I grab the values from the CSV they're treated as a string. I've tried using, Integer.parseInt(variable); and Double.parseDouble(variable);. I've tried troubleshooting with variable.getClass() and prints and I keep getting and I'm at a loss

my code is as follows:

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();

        }
    }
}

I get Exception in thread "main" java.lang.NumberFormatException: For input string: "4"

any help would be greatly appreciated

CodePudding user response:

It is likely that the columns / fields in the CSV file use double quotes " which need to be stripped off before splitting or parsing the integer value:

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

or

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

CodePudding user response:

It is better to use a CSV library to read CSV files. SuperCSV is a great option. Please refer the following link http://super-csv.github.io/super-csv/index.html

CodePudding user response:

Can be also some non-printable characters you've got in the lines of your ´.csv´

Try adding this filter to remove all of them:

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