Created
February 15, 2017 06:49
-
-
Save R00We/f417a789af3d0d81f8fb3596ee7280a9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
public class Main { | |
private static class Calculator { | |
private Calculator() { | |
} | |
public int calc(String string) { | |
String [] instance = string.split(" "); | |
Operation operation = Builder(instance[1]); | |
int digit1 = Integer.parseInt(instance[0]); | |
int digit2 = Integer.parseInt(instance[2]); | |
return operation.calculate(digit1, digit2); | |
} | |
public static Operation Builder(String operation) { | |
switch (operation){ | |
case "+": | |
return new Plus(); | |
case "-": | |
return new Minus(); | |
case "*": | |
return new Mult(); | |
case "/": | |
return new Split(); | |
default: | |
throw new RuntimeException("Operation not yet implemented"); | |
} | |
} | |
private interface Operation { | |
int calculate(int digit1, int digit2); | |
} | |
private static class Plus implements Operation { | |
@Override | |
public int calculate(int digit1, int digit2) { | |
return digit1 + digit2; | |
} | |
} | |
private static class Minus implements Operation { | |
@Override | |
public int calculate(int digit1, int digit2) { | |
return digit1 - digit2; | |
} | |
} | |
private static class Mult implements Operation { | |
@Override | |
public int calculate(int digit1, int digit2) { | |
return digit1 * digit2; | |
} | |
} | |
private static class Split implements Operation { | |
@Override | |
public int calculate(int digit1, int digit2) { | |
return digit1 / digit2; | |
} | |
} | |
} | |
public static void main(String[] args) { | |
Calculator calculator = new Calculator(); | |
if (calculator.calc("2 + 2") != 4) throw new RuntimeException(); | |
if (calculator.calc("2 - 2") != 0) throw new RuntimeException(); | |
if (calculator.calc("2 * 2") != 4) throw new RuntimeException(); | |
if (calculator.calc("2 / 2") != 1) throw new RuntimeException(); | |
System.out.print("Done"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment