Android: Java code for Tip Calculator
// Created by Bill Rosener
package com.example.tipCalculator;
import com.example.tipCalculator.R;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TipCalculator extends Activity {
EditText theInitialAmount;
TextView theTotalAmount, theTipAmount;
Button ButtonPoorService, ButtonAverageService, ButtonExcellentService;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
theInitialAmount = (EditText) findViewById(R.id.initialAmount);
theTipAmount = (TextView) findViewById(R.id.tipAmount);
theTipAmount.setText("0.00");
theTotalAmount = (TextView) findViewById(R.id.totalAmount);
theTotalAmount.setText("0.00");
ButtonPoorService = (Button) findViewById(R.id.poorService);
ButtonPoorService.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
calculatePoorService(theInitialAmount.getText());
}
});
ButtonAverageService = (Button) findViewById(R.id.averageService);
ButtonAverageService.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
calculateAverageService(theInitialAmount.getText());
}
});
ButtonExcellentService = (Button) findViewById(R.id.excellentService);
ButtonExcellentService.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
calculateExcellentService(theInitialAmount.getText());
}
});
}
protected void calculatePoorService(Editable first) {
float temp, tip, total;
double roundedTip;
temp = Float.parseFloat(first.toString());
tip = (float) (temp * 0.10);
roundedTip = Math.round(tip*100)/100.0d;
total = (float) (temp + roundedTip);
theTipAmount.setText(String.valueOf(roundedTip));
theTotalAmount.setText(String.valueOf(total));
}
protected void calculateAverageService(Editable first) {
float temp, tip, total;
double roundedTip;
temp = Float.parseFloat(first.toString());
tip = (float) (temp * 0.15);
roundedTip = Math.round(tip*100)/100.0d;
total = (float) (temp + roundedTip);
theTipAmount.setText(String.valueOf(roundedTip));
theTotalAmount.setText(String.valueOf(total));
}
protected void calculateExcellentService(Editable first) {
float temp, tip, total;
double roundedTip;
temp = Float.parseFloat(first.toString());
tip = (float) (temp * 0.20);
roundedTip = Math.round(tip*100)/100.0d;
total = (float) (temp + roundedTip);
theTipAmount.setText(String.valueOf(roundedTip));
theTotalAmount.setText(String.valueOf(total));
}
}