I am very new to Java as well as Android programming. I was attempting to make a calculator. But as soon as I inserted the square root button, the application crashes whenever I hit divide or square root. I don’t know where I’m going wrong. Help,please?
public class MainScreen extends Activity implements OnClickListener {
EditText edit1, edit2;
TextView txt;
Button butt, diff, mul, div, sqr, per;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edit1 = (EditText)findViewById(R.id.editText1);
edit2 = (EditText)findViewById(R.id.editText2);
txt = (TextView)findViewById(R.id.textView1);
butt = (Button)findViewById(R.id.button1);
butt.setOnClickListener(this);
diff = (Button)findViewById(R.id.button2);
diff.setOnClickListener(this);
mul = (Button)findViewById(R.id.button3);
mul.setOnClickListener(this);
div = (Button)findViewById(R.id.button4);
div.setOnClickListener(this);
sqr = (Button)findViewById(R.id.button5);
sqr.setOnClickListener(this);
per = (Button)findViewById(R.id.button6);
per.setOnClickListener(this);
}
@Override
public void onClick(View v) {
String a;
// TODO Auto-generated method stub
String b;
Integer sum, sub, mul, div;
Double x ;
a= edit1.getText().toString();
b= edit2.getText().toString();
x=(double) Integer.parseInt(a);
switch (v.getId()) {
case R.id.button1:
sum = Integer.parseInt(a)+ Integer.parseInt(b);
txt.setText(sum.toString());
break;
case R.id.button2:
sub = Integer.parseInt(a)- Integer.parseInt(b);
txt.setText(sub.toString());
break;
case R.id.button3:
mul = Integer.parseInt(a)* Integer.parseInt(b);
txt.setText(mul.toString());
break;
case R.id.button4:
div = (Integer.parseInt(a))/(Integer.parseInt(b));
txt.setText(div.toString());
case R.id.button5:
txt.setText((int) Math.sqrt(x));
default:
break;
}}}
It’s bad idea to use
(int) Math.sqrt(x)– sqrt does not return integer.When you write
textView.setText(int)– Andrid thinks, that you provide id of string resource, and it can’t find it and crashes.Use this: