I have an application which calculates the average from the values that users set. The problem is that I don't know if user sets 2,3 or all text fields with values, and I want my app to detect how many of them are filled and to divide the numbers entered to the number of how many fields are field. Example: If text field 1 = 2, and text field 2 = 3, my application should detect that there are only 2 fields filled, and to make the average from (2+3)/the number of how many text fields are filled, in our case 2. And beside that, I would like that my application to calculate the average exactly, I mean, to show values like 9.5 if the user enter 9 and 10 as values. Hope you understood exactly. Thanks a lot !!!

Here is my:

Medii.java:

package com.cngcnasaud.orar;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

public class Medii extends Activity {

    EditText txtNum1;
    EditText txtNum2;
    EditText txtNum4;
    EditText txtNum5;
    EditText txtTotal;
    Button btnCompute;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.medii);

        txtNum1 = (EditText) findViewById(R.id.editText1);
        txtNum2 = (EditText) findViewById(R.id.editText2);
        txtNum4 = (EditText) findViewById(R.id.editText4);
        txtNum5 = (EditText) findViewById(R.id.editText5);
        txtTotal = (EditText) findViewById(R.id.editText3);
        btnCompute = (Button) findViewById(R.id.bmedii);

        btnCompute.setOnClickListener(new ClickButton ());

    }


    private class ClickButton implements Button.OnClickListener{

        @Override
        public void onClick(View v) {

            int x = Integer.parseInt(txtNum1.getText().toString());
            int y = Integer.parseInt(txtNum2.getText().toString());
            int z = Integer.parseInt(txtNum4.getText().toString());
            int w = Integer.parseInt(txtNum5.getText().toString());

            int total = (x + y + z + w)/4;

            txtTotal.setText(Integer.toString(total));

        }


    }

}
有帮助吗?

解决方案

int countOfValues = (x == 0 ? 0 : 1) + (y == 0 ? 0 : 1) + (z == 0 ? 0 : 1) + (w == 0 ? 0 : 1);
double total = (x + y + z + w)/(double)countOfValues;

txtTotal.setText(Double.toString(total));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top