Code Snippet 9 of /src/com/examples/tipcalc/Tipster.java
  1. /**
  2.  * Calculate the tip as per data entered by the user.
  3.  */
  4. private void calculate() {
  5.     Double billAmount = Double.parseDouble(
  6.         txtAmount.getText().toString());
  7.     Double totalPeople = Double.parseDouble(
  8.         txtPeople.getText().toString());
  9.     Double percentage = null;
  10.     boolean isError = false;
  11.     if (billAmount < 1.0) {
  12.         showErrorAlert("Enter a valid Total Amount.",
  13.             txtAmount.getId());
  14.         isError = true;
  15.     }
  16.  
  17.     if (totalPeople < 1.0) {
  18.         showErrorAlert("Enter a valid value for No. of people.",
  19.             txtPeople.getId());
  20.         isError = true;
  21.     }
  22.  
  23.     /*
  24.      * If user never changes radio selection, then it means
  25.      * the default selection of 15% is in effect. But its
  26.      * safer to verify
  27.      */
  28.     if (radioCheckedId == -1) {
  29.         radioCheckedId = rdoGroupTips.getCheckedRadioButtonId();
  30.     }
  31.     if (radioCheckedId == R.id.radioFifteen) {
  32.         percentage = 15.00;
  33.     } else if (radioCheckedId == R.id.radioTwenty) {
  34.         percentage = 20.00;
  35.     } else if (radioCheckedId == R.id.radioOther) {
  36.         percentage = Double.parseDouble(
  37.             txtTipOther.getText().toString());
  38.         if (percentage < 1.0) {
  39.             showErrorAlert("Enter a valid Tip percentage",
  40.                 txtTipOther.getId());
  41.             isError = true;
  42.         }
  43.     }
  44.     /*
  45.      * If all fields are populated with valid values, then proceed to
  46.      * calculate the tips
  47.      */
  48.     if (!isError) {
  49.         Double tipAmount = ((billAmount * percentage) / 100);
  50.         Double totalToPay = billAmount + tipAmount;
  51.         Double perPersonPays = totalToPay / totalPeople;
  52.  
  53.         txtTipAmount.setText(tipAmount.toString());
  54.         txtTotalToPay.setText(totalToPay.toString());
  55.         txtTipPerPerson.setText(perPersonPays.toString());
  56.     }
  57. }
Tutorials