Reputation: 184
I am building a simple Calculator in Android. I have three parameters namely, firstNumber
, secondNumber
and operation
to be performed. It can be easily done using if-else block, but as its not a good and scalable solution (considering I will add more features in future), I was trying to use Java OOPs features (interfaces or so).
I know its a very trivial problem, but being a beginner I am unable to do it.
// Common Interface
public interface ComputationInterface {
public String compute(int firstNum,
int secondNum);
}
// Addition
public class Add implements ComputationInterface{
public String compute(int firstNum, int secondNum){
int sum = firstNum + secondNum;
return Integer.toString(sum);
}
}
// Subtraction
public class Divide implements ComputationInterface{
public String compute(int firstNum, int secondNum){
if(secondNum == 0)
return "Division by ZERO undefined";
int quotient = firstNum/secondNum;
int remainder = firstNum % secondNum;
return String.format("%d R: %d", quotient, remainder);
}
}
// Multiplication
public class Multiply implements ComputationInterface{
public String compute(int firstNum, int secondNum){
int resultNum = firstNum * secondNum;
return Integer.toString(resultNum);
}
}
// Division
public class Subtract implements ComputationInterface{
public String compute(int firstNum, int secondNum){
int diffNum = firstNum - secondNum;
return Integer.toString(diffNum);
}
}
/* Code Snippet from where I have to call above operations */
private static final int ADD = 1;
private static final int SUB = 2;
private static final int MUL = 3;
private static final int DIV = 4;
/**
* 'operation' param corresponds to one of the four arithmetic
* operations listed above.
*/
public void performCalculation(int argumentOne, int argumentTwo, int operation){
// TODO: Help Needed
}
EDIT
The solution I am looking for is I will make a call on some Java object, passing three parameters to it, as below
String result = SomeJavaObject.doCompuation(int argumentOne, int argumentTwo,
int operation);
Moreover, I want the solution to be scalable enough, so I can easily add new features like log, power etc. by creating new java classes/interfaces etc.
Upvotes: 0
Views: 562
Reputation: 140427
One thing you can do - change your interface to:
public int compute(int... arguments)
Upvotes: 0
Reputation: 533500
I have used an enum
for this in the past.
public enum Ops implements ComputationInterface {
Add('+') {
public Object compute(long firstNum, long secondNum){
return firstNum + secondNum;
}
},
Subtract('-') {
...
},
Multiply('*') {
},
Divide('/') {
public Object compute(long firstNum, long secondNum){
if (secondNum == 0)
return "Division by ZERO undefined";
long quotient = firstNum / secondNum;
long remainder = firstNum % secondNum;
return remainder == 0 ? quotient : String.format("%d R: %d", quotient, remainder);
}
}
}
Upvotes: 1