【问题标题】:Java, working with filesJava,处理文件
【发布时间】:2013-12-28 13:29:34
【问题描述】:

我有一个文本文件

category1 1 10 101 1 good1
category6 2 11 105 2 good5
category1 5 13 103 3 good4
category3 6 14 102 4 good2
category5 3 12 107 2 good1

如何阅读第 5 列?我需要找到其中元素的总和,但我不知道如何阅读它。这是我所做的:

    int sum = 0;
    BufferedReader br = new BufferedReader(new FileReader("/Data.txt"));
    String line = br.readLine();
    String[] columns = line.split(" ");
    String[] items = columns[4].split(" ");
    for(int i = 0; i<items.length; i++){
        sum = sum + Integer.parseInt(items[i]);
    }

但它不起作用

【问题讨论】:

  • 您需要比“不起作用”更具体。

标签: java string file


【解决方案1】:

您只是在读取文件的第一行。使用:

int sum = 0;
BufferedReader br = new BufferedReader(new FileReader("/Data.txt"));
String line;
while ((line = br.readLine()) != null)
{
    String[] columns = line.split(" ");
    sum = sum + Integer.parseInt(columns[4]);        
}

【讨论】:

    【解决方案2】:
    int sum = 0;
        BufferedReader br = new BufferedReader(new FileReader("/Data.txt"));
    String line = "";
    while((line=br.readLine())!=null){
    String[] columns = line.split(" ");
    
    
        sum = sum + Integer.parseInt(columns[4]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-01
      • 2017-11-05
      • 2015-03-08
      • 1970-01-01
      • 2011-09-10
      • 2012-07-29
      • 1970-01-01
      • 2020-08-25
      相关资源
      最近更新 更多