简体   繁体   English

从字符串中提取数字[]

[英]extract numbers from String[]

I have an array rawData[] which contains strings from a csv file. 我有一个rawData[]数组,其中包含来自csv文件的字符串。 What I want to do now, is to copy all the Integers saved as Strings to a new int[]. 我现在要做的是将所有保存为字符串的Integer复制到新的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 最后一次Try / Catch的错误“从未在相应的try块中引发异常'java.io.IOException'

  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? 当我尝试将dataList转换为数组时,我得到:“ Incompatible types. Found: 'java.lang.Object[]', required: 'int[]' ”我知道arraylist某种程度上包含对象,但是我如何获得那工作吗?


     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. Integer.parseInt(s) doesn't throw an IOException . Integer.parseInt(s)不抛出IOException It throws a NumberFormatException . 它抛出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()]); List.toArray无法产生基本类型的数组,因此您必须将其更改为Integer[] data = dataList.toArray(new Integer[dataList.size()]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM