我这里有这个代码,它从文件中读取数字并将它们存储在String数组中。
public static void main(String [] args) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("/Users/Tda/desktop/ReadFiles/scores.txt"));
String line = null;
while((line = br.readLine()) != null){
String[] values = line.split(",");
for(String str : values){
System.out.println(str);
}
}
System.out.println("");
br.close();
}
但是如果我想将String数组中的值存储在int数组中,我该怎么办?
我正在阅读的文件看起来像这样。
23,64,73,26
75,34,21,43
答案 0 :(得分:1)
使用parseInt(String)将每个字符串转换为int http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29
int[] intvalues = new int[values.length];
for (int i = 0; i < values.length; i++) {
intvalues[i] = Integer.parseInt(values[i]);
}
答案 1 :(得分:1)
String[] values = line.split(",");
之后...
// new int[] with "values"'s length
int[] intValues = new int[values.length];
// looping over String values
for (int i = 0; i < values.length; i++) {
// trying to parse String value as int
try {
// worked, assigning to respective int[] array position
intValues[i] = Integer.parseInt(values[i]);
}
// didn't work, moving over next String value
// at that position int will have default value 0
catch (NumberFormatException nfe) {
continue;
}
}
...并测试:
System.out.println(Arrays.toString(intValues));
答案 2 :(得分:1)
您需要将string
解析为int
:
while((line = br.readLine()) != null){
String[] values = line.split(",");
int[] values2=new int[values.length];
for(int i=0; i<values.length; i++){
try {
values2[i]= Integer.parseInt(values[i]);
//in case it's not an int, you need to try catching a potential exception
}catch (NumberFormatException e) {
continue;
}
}
}