Java 从以逗号分隔的文件中读取int
我这里有一段代码,它从文件中读取数字并将其存储在字符串数组中Java 从以逗号分隔的文件中读取int,java,bufferedreader,Java,Bufferedreader,我这里有一段代码,它从文件中读取数字并将其存储在字符串数组中 public static void main(String [] args) throws Exception{ BufferedReader br = new BufferedReader(new FileReader("/Users/Tda/desktop/ReadFiles/scores.txt")); String line = null;
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();
}
但是如果我想将字符串数组中的值存储在int数组中,我应该怎么做呢
我正在读的文件看起来像这样
23,64,73,26
75,34,21,43
使用parseInt(String)将每个字符串转换为int
int[]intvalues=newint[values.length];
对于(int i=0;i
在String[]值=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;
}
}
您需要将字符串
解析为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;
}
}
}
while((line=br.readLine())!=null){
字符串[]值=行。拆分(“,”);
int[]values2=新的int[values.length];
for(int i=0;我想把所有的值放在一个int数组中,还是想为文件中的每一行单独设置一个int数组?实际上,每一行一个数组,但所有行一个数组也可以。for循环中的值应该是values.length,而不是values.length()很好!完全忽略了这一点。
System.out.println(Arrays.toString(intValues));
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;
}
}
}