从String []中提取数字

时间:2016-05-16 08:00:03

标签: java arrays string arraylist int

我有一个数组rawData[],其中包含csv文件中的字符串。 我现在要做的是将保存为字符串的所有整数复制到新的int []。

我尝试了下面的代码但是我遇到了两个错误。

  1. 错误"异常' java.io.IOException'永远不会被扔进相应的试块#34;最后一次尝试/捕获

  2. 当我尝试将dataList转换为数组时,我得到:" Incompatible types. Found: 'java.lang.Object[]', required: 'int[]'" 我知道arraylist不知何故包含对象,但我怎么能让它工作?

  3.      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;
    

1 个答案:

答案 0 :(得分:2)

  1. Integer.parseInt(s)不会抛出IOException。它会抛出NumberFormatException

  2. List.toArray无法生成基本类型的数组,因此您必须将其更改为Integer[] data = dataList.toArray(new Integer[dataList.size()]);