Reputation: 13
Basically I have four EditText fields lets call them apple, pear, banana and orange. The user enters how many of each were bought then when you press a button it calculates the total fruit.
public class Fruit extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fruit);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("Enter amount of fruit bought");
}
public void onButtonClick(View v) {
EditText a = (EditText)findViewById(R.id.editText3);
EditText p = (EditText)findViewById(R.id.editText5);
EditText b = (EditText)findViewById(R.id.editText4);
EditText o = (EditText)findViewById(R.id.editText6);
TextView sum = (TextView)findViewById(R.id.textView3);
float apple = Float.parseFloat(a.getText().toString());
float pear = Float.parseFloat(p.getText().toString());
float banana = Float.parseFloat(b.getText().toString());
float orange = Float.parseFloat(o.getText().toString());
float total;
total=apple+pear+banana+orange;
sum.setText(Float.toString(total));
}}
How do I go about making sure if the user leaves a field blank the program treats it as 0 and still gives the total fruit bought?
Upvotes: 0
Views: 32
Reputation: 539
private String ensureFruit(String str){
return TextUtils.isEmpty(str)? "0": str;
}
and use it as
float apple = Float.parseFloat(ensureFruit(a.getText().toString()));
Upvotes: 1