I am writing a simple java program to perform Addition and Multiplication using Object Oriented technique. First it asks about the operation Addition, Multiplication or Exit. When Addition and Multiplication button is pressed it gets two numbers from user, performs the task and gives the result.But my problem is when Exit button is pressed it does not terminates instead it ask for numbers.
And second thing which i want to ask is that am i following the Object Oriented approach.
import javax.swing.JOptionPane;
public class Calculator {
private static int number1;
private static int number2;
public static void setNumber1(int n1) {
number1 = n1;
}
public static void setNumber2(int n2) {
number2 = n2;
}
public static int getNumber1() {
return number1;
}
public static int getNumber2() {
return number2;
}
public static void numbers(){
int n=Integer.parseInt(JOptionPane.showInputDialog("Enter first number:"));
int nn=Integer.parseInt(JOptionPane.showInputDialog("Enter first number:"));
setNumber1(n);
setNumber2(nn);
}
public static void calculate(int o){
switch(o){
case 0:
JOptionPane.showMessageDialog(null, "Addition is :"+(number1+number2));
break;
case 1:
JOptionPane.showMessageDialog(null, "Product is :"+(number1*number2));
break;
case 2:
System.exit(0);
break;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//Custom button text
Object[] options = {"Addition","Product", "Exit!"};
int op = JOptionPane.showOptionDialog(null,"What operation Would you like to perform ?","Addition or Product Calculator",
JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,
null,options,options[2]);
Calculator c=new Calculator();
c.numbers();
c.calculate(op);
}
}
static methods, I vote for no on the OOP. The only static method you should have here ismain.Code Review. codereview.stackexchange.comc.numbers();and thenc.calculate(op);so that's why it does not exit before asking for numbers. Change this order if you want other functionalitystaticreally means. Spoiler: it is not the same asfinal. But if you think that ... isn't it strange that you can declarenumber1asstaticand change it's value in thesetNumber1method?