I develop an application where spinner contains add, sub, mul & div… but the result always gives zero. How I develop the app when button clicked the calculation solved depends upon the selected value of the spinner. The code is below::
public void Select(View view)
{
TextView txt1=(TextView)findViewById(R.id.editText1);
TextView txt2=(TextView)findViewById(R.id.editText2);
int x=Integer.parseInt(txt1.getText().toString());
int y=Integer.parseInt(txt2.getText().toString());
Spinner spin1=(Spinner)findViewById(R.id.spinner1);
String spin_value= spin1.getItemAtPosition(spin1.getSelectedItemPosition()).toString();
if(spin_value=="Add")
{
int z=x+y;
String addvalue=String.valueOf(z);
Toast.makeText(this, addvalue, Toast.LENGTH_LONG).show();
}
else if (spin_value=="Sub")
{
int p=x-y;
String subvalue=String.valueOf(p);
Toast.makeText(this, subvalue, Toast.LENGTH_LONG).show();
}
else if (spin_value=="Mul")
{
int k=x*y;
String mulvalue=String.valueOf(k);
Toast.makeText(this, mulvalue, Toast.LENGTH_LONG).show();
}
else
{
int g=x/y;
String divvalue=String.valueOf(g);
Toast.makeText(this, divvalue, Toast.LENGTH_LONG).show();
}
}
}
Bob Kaufman’s comment is correct. You are falling through to your
elsestatement by virtue of the comparisons you are making. To compare strings in Java you should use theequals(Object o)orequalsIgnoreCasemethods, not==unless you want to determine if the Strings being compared are the same object.On top of that, it’s not really clear what is being returned by
getItemAtPositionsince we can’t see what kind ofSpinnerAdapteryou are using. So, it may not even be appropriate to do theStringcomparisons in the first place.Like, Bob, I suspect you are getting 0 because of integer division. If you put, say, 100 in txt1 and, say, 40, in txt2, I would guess your Toast would read
2.