我正在编写一个简单的Java程序,以使用面向对象的技术执行加法和乘法。首先,它询问有关加法,乘法或退出的操作。当按下加法和乘法按钮时,它会从用户那里获得两个数字,执行任务并给出结果。但是我的问题是,当按下退出按钮时,它不会终止,而是要求输入数字。
我想问的第二件事是我是否遵循面向对象的方法。
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);
}
}
最佳答案
程序无法退出的问题是您正在调用numbers
方法,该方法在calculate
方法中的检查选项之前读取数字。因此,可以通过使用numbers
进行检查来防止在op = 2
时调用if
方法。
做到这一点的代码是:
Calculator c=new Calculator();
if(op!=2) {
c.numbers();
}
c.calculate(op);