繁体   English   中英

从用逗号分隔的文件中读取int

[英]Read int from file separated by comma

我这里有这个代码,它从文件中读取数字并将它们存储在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

使用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]);
    }

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));

您需要将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;
               }
               }


 }

暂无
暂无

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

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