Java 从字符串[]中提取数字
我有一个数组Java 从字符串[]中提取数字,java,arrays,string,arraylist,int,Java,Arrays,String,Arraylist,Int,我有一个数组rawData[],其中包含来自csv文件的字符串。 我现在要做的是将所有保存为字符串的整数复制到一个新的int[] 我尝试了下面的代码,但出现了两个错误 对于最后一次尝试/捕获,错误“Exception'java.io.IOException'从未在相应的try块中抛出” 当我尝试将数据列表转换为数组时,我得到:“不兼容的类型。找到:'java.lang.Object[],必需:'int[]”” 我知道arraylist以某种方式包含对象,但我如何才能使其工作 publicsta
rawData[]
,其中包含来自csv文件的字符串。
我现在要做的是将所有保存为字符串的整数复制到一个新的int[]
我尝试了下面的代码,但出现了两个错误
数据列表
转换为数组时,我得到:“不兼容的类型。找到:'java.lang.Object[],必需:'int[]”
”
我知道arraylist以某种方式包含对象,但我如何才能使其工作publicstatic int[]getData(){
String csvFile=“C:\\Users\\Joel\\Downloads\\csgodoubableanalyze.csv”;
BufferedReader br=null;
字符串行=”;
字符串cvsSplitBy=“,”;
String[]rawData=新字符串[0];
List dataList=new ArrayList();
试一试{
br=新的BufferedReader(新的文件读取器(csvFile));
而((line=br.readLine())!=null){
//使用逗号作为分隔符
rawData=行分割(cvsSplitBy);
}
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}最后{
如果(br!=null){
试一试{
br.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
for(字符串s:rawData){
试一试{
add(Integer.parseInt(s));
}
捕获(IOE异常){
e、 printStackTrace();
}
}
int[]data=dataList.toArray();
返回数据;
Integer.parseInt
不会引发IOException
。它会引发NumberFormatException
List.toArray
无法生成基元类型的数组,因此必须将其更改为Integer[]data=dataList.toArray(新整数[dataList.size());
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;