jobr97
jobr97

Reputation: 179

extract numbers from String[]

I have an array rawData[] which contains strings from a csv file. What I want to do now, is to copy all the Integers saved as Strings to a new int[].

I tried the code below but I get two errors.

  1. Error "Exception 'java.io.IOException' is never thrown in the corresponding try block" for the last Try/Catch

  2. When I try to convert the dataList to an array I get: "Incompatible types. Found: 'java.lang.Object[]', required: 'int[]'" I know that somehow the arraylist contains objects but how can I get that to work?


     public static int[] getData(){
                String csvFile = "C:\\Users\\Joel\\Downloads\\csgodoubleanalyze.csv";
                BufferedReader br = null;
                String line = "";
                String cvsSplitBy = ",";
                String[] rawData = new String[0];
                List<Integer> dataList = new ArrayList<Integer>();

                try {

                    br = new BufferedReader(new FileReader(csvFile));
                    while ((line = br.readLine()) != null) {

                        // use comma as separator
                        rawData = line.split(cvsSplitBy);
                    }

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                for (String s : rawData){
                    try {
                        dataList.add(Integer.parseInt(s));
                    }
                    catch (IOException e){
                        e.printStackTrace();
                    }
                }

                int[] data = dataList.toArray();

                return data;

Upvotes: 1

Views: 104

Answers (1)

Eran
Eran

Reputation: 393791

  1. Integer.parseInt(s) doesn't throw an IOException. It throws a NumberFormatException.

  2. List.toArray can't produce an array of primitive type, so you'll have to change it to Integer[] data = dataList.toArray(new Integer[dataList.size()]);

Upvotes: 2

Related Questions