Ugly code/beautiful code -- for +, and - int PLUS=0;
int MINUS=1;
int EQUALS=2;
int state=PLUS; // first operator is by default +
void plusProto() {
String s = inTF.getText();
int currentInput = Integer.parseInt(s);
// now apply the *previous* operator with the current input
if (state == PLUS) {
total = total + currentInput;
}
else if (state == MINUS) {
total = total - currentInput;
}
else if (state == EQUALS) {
}
else {
System.out.println("oops, *not* equal, plus or minus??");
}
state = PLUS;
inTF.setText(""+total);
inTF.requestFocus();
inTF.selectAll();
}
void minusProto() {
String s = inTF.getText();
int currentInput = Integer.parseInt(s);
// now apply the *previous* operator with the current input
if (state == PLUS) {
total = total + currentInput;
}
else if (state == MINUS) {
total = total - currentInput;
}
else if (state == EQUALS) {
}
else {
System.out.println("oops, *not* equal, plus or minus??");
}
state = MINUS;
inTF.setText(""+total);
inTF.requestFocus();
inTF.selectAll();
}What's wrong with this? Too long! Plus, the only difference is the state = PLUS and state = MINUS. So... int currentInput;
int PLUS=0;
int MINUS=1;
int EQUALS=2;
int state=PLUS; // first operator is by default +
void setCurrentInput() {
String s = inTF.getText();
currentInput = Integer.parseInt(s);
}
void plusProto() {
setCurrentInput();
updateTotal();
displayTotal();
state = PLUS;
}
void minusProto() {
setCurrentInput();
updateTotal();
displayTotal();
state = MINUS;
}
void updateTotal() {
// apply the *previous* operator with the current input
if (state == PLUS) {
total = total + currentInput;
}
else if (state == MINUS) {
total = total - currentInput;
}
else if (state == EQUALS) {
}
else {
System.out.println("oops, *not* equal, plus or minus??");
}
}
void displayTotal() {
inTF.setText(""+total);
inTF.requestFocus();
inTF.selectAll();
} Which is quite a bit better... but... minusProto and plusProto are all the same code but one line, so...
int PLUS=0;
int MINUS=1;
int EQUALS=2;
int state=PLUS; // first operator is by default +
int currentInput;
void setCurrentInput() {
String s = inTF.getText();
currentInput = Integer.parseInt(s);
}
void plus() {
update();
state = PLUS;
}
void minus() {
update();
state = MINUS;
}
void update() {
setCurrentInput();
updateTotal();
displayTotal();
}
void updateTotal() {
// apply the *previous* operator with the current input
if (state == PLUS) {
total = total + currentInput;
}
else if (state == MINUS) {
total = total - currentInput;
}
else if (state == EQUALS) {
}
else {
System.out.println("oops, *not* equal, plus or minus??");
}
}
void displayTotal() {
inTF.setText(""+total);
inTF.requestFocus();
inTF.selectAll();
}