affanBajwa
affanBajwa

Reputation: 168

System.exit(0) not working & Object Oriented Design.

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);
}

}

Upvotes: 0

Views: 179

Answers (2)

Johny
Johny

Reputation: 2188

The problem that your program wont exit is that you are calling the numbers method which reads the numbers before the checking options in the calculate method. So you can prevent calling of numbers method when op = 2 by checking it with an if.
code to do that is:

Calculator c=new Calculator();
if(op!=2) {
   c.numbers();
}
c.calculate(op);

Upvotes: 1

user3922145
user3922145

Reputation: 39

The reason why it asks for numbers is because you are calling the method numbers() before calculate(int o). You have to switch the order but with some modifications to your code.

And about OOP, Java is purely OOP. But to get the most out of it read and exercise more on the object oriented concepts like inheritance, interfaces ...

Upvotes: 0

Related Questions