-3

I am the beginner of the Android SDK programming.

What I have is,a calculator that doesn't show decimals when i press calculate button and is there if there is any way to do it?Also crashes if I didn't fill the EditText.

    Button cal;
EditText n1,n2,n3;
TextView answer;

int x,y,r,z;

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

    answer = (TextView)findViewById(R.id.res);
    n1 = (EditText)findViewById(R.id.n1);
    n2 = (EditText)findViewById(R.id.n2);
    n3 = (EditText)findViewById(R.id.n3);
    cal = (Button)findViewById(R.id.calc);

    cal.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            x=Integer.parseInt(n1.getText().toString());
            y=Integer.parseInt(n2.getText().toString());
            z=Integer.parseInt(n3.getText().toString());
            r=(x+y+z)/3;

            answer.setText("" + r);
        }
    });
Kamal Muradov
  • 49
  • 1
  • 1
  • 10
  • please learn java's basics: how division works with integers ... and about crash - you should validate input before parsing – Selvin Dec 07 '17 at 19:56
  • You're using integers. Read up on primitive types from the docs: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html – denvercoder9 Dec 07 '17 at 19:57
  • This is how to allow decimals in an editText [answerLink](https://stackoverflow.com/a/7543859/4224839) – Edward DiGirolamo Dec 07 '17 at 19:58
  • Possible duplicate of [Division of integers in Java](https://stackoverflow.com/questions/7220681/division-of-integers-in-java) – Amit Vaghela Dec 08 '17 at 13:39

1 Answers1

1

You are using Integer.parseInt , to get decimal use Double.parseDouble

set this for edit texts -

n1.setInputType(InputType.TYPE_CLASS_NUMBER);
n2.setInputType(InputType.TYPE_CLASS_NUMBER);
n3.setInputType(InputType.TYPE_CLASS_NUMBER);

for crashing put checks that user can calculate only when edit texts have values

cal.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if(!n1.getText().toString().isEmpty()&&!n2.getText().toString().isEmpty()&&!n3.getText().toString().isEmpty())
        calculateResult();
 else{ //show error message
      }

    }
});



public void calculateResult()
{
      x=Double.parseDouble(n1.getText().toString());
        y=Double.parseDouble(n2.getText().toString());
        z=Double.parseDouble(n3.getText().toString());
        r=(x+y+z)/3;

        answer.setText("" + r);
 }

and change data types of x,y,z,r to double

Apoorv Singh
  • 1,295
  • 1
  • 14
  • 26