Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

java - Calculating sum of numbers from a file?

I want to show the sum of all prices (e.g. £18.99 £50 etc.) from a file in a TextView, currently it just reads/shows the last price from the file.

This is my current code for writing to a file:

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

This is my current code for reading from a file (member burmat suggested some changes):

public void savingstotalbutton(View view) {

        double total = 0;

        try {
            BufferedReader inputReader = new BufferedReader(new InputStreamReader(
                    openFileInput("TotalSavings")));
            String inputString;
            @SuppressWarnings("unused")
            StringBuffer stringBuffer = new StringBuffer();                
            while ((inputString = inputReader.readLine()) != null) {

                if (inputString.length() > 0) {
                String line = inputString.replaceAll("[^0-9.]", "");
                total = total + Double.parseDouble(line);
                }
            }
            savingstotaltext.setText(String.valueOf(total));
        } catch (IOException e) {
            e.printStackTrace();
        }               
    }

Any help is appreciated.

Edit: I modified the contents of the TotalSavings.txt manually and added different prices and copied that to the /files folder of the App. It reads all the prices and gives the sum which works but the problem is that the write function overwrites the 1st line, it never goes to the next line.

Edit 2: The whole code which uses calc button to show calculation and the write the result to the file TotalSavings.txt

public void calc(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        if (price.getText().toString().equals(""))
            return;
        if (disc.getText().toString().equals(""))
            return;
        double priceVal = Double.parseDouble(price.getText().toString());
        double discVal = Double.parseDouble(disc.getText().toString());
        double discount = priceVal / 100.0 * discVal;
        int di = (int) (discount * 100);
        double totalVal = priceVal - (di / 100.0);
        NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.getDefault());
        savings.setText(nf.format(discount));
        total.setText(nf.format(totalVal));

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

    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The answer to your problem with writing to the file is every time you are writing to the file you are over writing what was there before, what you need to do is change

FileOutputStream fos = openFileOutput("TotalSavings", Context.MODE_PRIVATE)

to:

FileOutputStream fos = openFileOutput("TotalSavings", Context.MODE_PRIVATE | Context.MODE_APPEND)

This tells android you want to append to the file as well as keep it private.

EDIT You new issue is because you are placing the text directly after the other text, you want to force a new line into your file. The simplest way will be something like:

String totalFromField = total.getText().toString() + "
";
fos.write(totalFromField.getBytes());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...