【问题标题】:How to calculate sum of numbers from a file?如何计算文件中的数字总和?
【发布时间】:2012-11-06 14:41:55
【问题描述】:

我想在 TextView 中显示从文件中添加的所有数字的总和,目前它只是读取/显示文件中的最后一个数字。

这是我当前写入文件的代码:

total.setText(total.getText());                            
        try {
            FileOutputStream fos = openFileOutput("TotalSavings", Context.MODE_PRIVATE);
            fos.write(total.getText().toString().getBytes());
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

这是我当前读取文件的代码:

public void savingstotalbutton(View view) {

        try {
            BufferedReader inputReader = new BufferedReader(new InputStreamReader(
                    openFileInput("TotalSavings")));
            String inputString;
            StringBuffer stringBuffer = new StringBuffer();                
            while ((inputString = inputReader.readLine()) != null) {
                stringBuffer.append(inputString + "\n");
            }
            savingstotaltext.setText(stringBuffer.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }               
    }

谁能告诉我怎么做?

【问题讨论】:

标签: java android filereader


【解决方案1】:

假设行中唯一的东西是一个整数,你不能做这样的事情吗?

public void savingstotalbutton(View view) {

    int total = 0;

    try {
        BufferedReader inputReader = new BufferedReader(new InputStreamReader(
                openFileInput("TotalSavings")));
        String inputString;
        StringBuffer stringBuffer = new StringBuffer();                
        while ((inputString = inputReader.readLine()) != null) {
            //stringBuffer.append(inputString + "\n");
            total = total + Integer.parseInt(inputString);
        }
        //savingstotaltext.setText(stringBuffer.toString());
        savingstotaltext.setText(String.ValueOf(total));
    } catch (IOException e) {
        e.printStackTrace();
    }               
}

编辑: cmets 中每个问题的扩展答案

如果您使用小数,只需将int total 更改为double total 并将Integer.parseInt() 更改为Double.parseDouble()。此外,如果行上的字符多于数字/小数,请尝试使用以下内容仅去除并使用数字,并确保行上有内容:

if (inputString.length() > 0) {
    String line = inputString.replaceAll("[^0-9.]", "");
    total = total + Double.parseDouble(line);
}

【讨论】:

  • 谢谢你,但数字不是整数,它们是价格,例如18.95 英镑、50 英镑等,所以我必须将其更改为双倍吗?
  • 是的,只要您没有任何其他字符,例如:£,那应该没问题。如果这样做,则需要删除任何其他字符以确保从 string 的数据类型转换成功。
  • @OlympicBeast 我编辑了我的答案,为您指明了正确的方向。如果您需要任何澄清,请告诉我。如果我的回答对你有帮助,请采纳。
  • 抱歉刚刚看到您的编辑。我也在 E​​clipse LogCat 上看到这个错误:java.lang.IllegalStateException:无法执行活动的方法
  • @OlympicBeast 听起来好像从那个错误中你在某处有一个空值。确保所有变量都已初始化且一致。这可能是因为您试图从空值(空行)解析双精度/整数。请参阅我的编辑以及剥离货币符号。使用replaceAll(),您可以只去除数字/小数。
猜你喜欢
  • 1970-01-01
  • 2012-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多