I get 0.0 every time I divide… here is a solution to the problem.
I get 0.0 every time I divide
I’m trying to make an app that distributes bills between people, but it always gives me 0.0 whenever I try to divide two numbers in the code. Why is that?
The code is as follows:
public class MainActivity extends Activity {
public int x = 0;
public double y = 1.00;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button
Button btn = (Button) findViewById(R.id.button);
EditText
EditText nop = (EditText) findViewById(R.id.editText);
EditText cob = (EditText) findViewById(R.id.editText2);
try{
x = Integer.valueOf(nop.getText().toString());
} catch (NumberFormatException e) {
x = 0;
}
try{
y = Double.valueOf(cob.getText().toString());
} catch (NumberFormatException e) {
y = 1.00;
}
TextView
final TextView tv = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Double z = (y / x);
tv.setText("You will each pay:" + (z));
}
});
}
}
Solution
My guess is that you don’t evaluate these values after clicking. Your try/catch code should be in the onclick method.