Last active
November 11, 2020 05:02
-
-
Save hoangtuan151/7105ce9d9c458733c9387650eb311e0c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Generic part | |
// | |
public abstract class SimpleCalculator { | |
private static PrintStream log = System.out; | |
private static Scanner cs = new Scanner(System.in); | |
protected int num1, num2; | |
protected int result; | |
public void takeAction() { | |
log.println("Enter 1st number:"); | |
String num1 = cs.nextLine(); | |
log.println("Enter 2nd number:"); | |
String num2 = cs.nextLine(); | |
this.num1 = Integer.parseInt(num1); | |
this.num2 = Integer.parseInt(num2); | |
this.result = doCalculate(this.num1, this.num2); | |
printResult(); | |
} | |
protected abstract int doCalculate(int num1, int num2); | |
protected abstract void printResult(); | |
} | |
// | |
// Tailored part | |
// | |
public class Add extends SimpleCalculator { | |
private static PrintStream log = System.out; | |
protected int doCalculate(int num1, int num2) { | |
return num1 + num2; | |
} | |
protected void printResult() { | |
log.format("The ADD result: %d + %d = %d", this.num1, this.num2, this.result); | |
} | |
} | |
public class Sub extends SimpleCalculator { | |
private static PrintStream log = System.out; | |
protected int doCalculate(int num1, int num2) { | |
return num1 - num2; | |
} | |
protected void printResult() { | |
log.format("The SUB result: %d - %d = %d", this.num1, this.num2, this.result); | |
} | |
} | |
// Main entrypoint | |
public class Main { | |
private static PrintStream log = System.out; | |
private static Scanner cs = new Scanner(System.in); | |
public static void main(String[] args) { | |
log.println("!~ SIMPLE CALCULATOR ~!"); | |
log.println("Choose arithmetic operations (+ or -):"); | |
String operation = cs.nextLine(); | |
if (operation.equals("+")) { | |
Add addInst = new Add(); | |
addInst.takeAction(); | |
} else if (operation.equals("-")) { | |
Sub subInst = new Sub(); | |
subInst.takeAction(); | |
} else { | |
log.println("Not supported!"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment