重新打开正在运行的java程序

时间:2014-04-08 16:59:20

标签: java swing jframe

我有一个我一直在上学的计算器。

虽然它不会有典型的计算器GUI。

我有一个测试版,我使用输入框来获取输入。

我实际上想知道是否有办法让函数关闭它,然后重新打开它就像一个循环。

import javax.swing.JOptionPane;

public class JOptionPaneCalc {

public static void main(String [] args){

    char o = ' ';
    String input = " ";
    double num1 = 0;
    double num2 = 0;
    double result = 0;


    while (true){

    input = JOptionPane.showInputDialog("What is your operand? ");
    o = input.charAt(0); 

    if (o == '/') {
        result = num1 / num2;
        break;
    } else if (o == '*') {
        result = num1 * num2;
        break;
    } else if (o == '+') {
        result = num1 + num2;
        break;
    } else if (o == '-') {
        result = num1 - num2;
        break;
    }else if (o == 'q'){
        System.exit(0);
    }


    }

    input = JOptionPane.showInputDialog("What is your first number? ");
    num1 = Double.parseDouble(input);

    input = JOptionPane.showInputDialog("What is your second number? ");
    num2 = Double.parseDouble(input);

    if (o == '/') {
        result = num1 / num2;

    } else if (o == '*') {
        result = num1 * num2;

    } else if (o == '+') {
        result = num1 + num2;

    } else if (o == '-') {
        result = num1 - num2;

    }else if (o == 'q'){
        System.exit(0);
    }

    JOptionPane.showMessageDialog(null ,"Your answer is : " + result);


}   

}

这就是我所拥有的,希望你能帮助我

1 个答案:

答案 0 :(得分:1)

您的代码存在很多问题。如果o =='q',那么你的程序将退出。

}else if (o == 'q'){
    System.exit(0);
}

了解重复。 如果你想让你的程序循环,那么你应该写它至少这样:

 public static void main(String[] args) {

    char o;
    String input;
    double num1;
    double num2;
    double result=0.;

    input = JOptionPane.showInputDialog("What is your operand? ");
    o = input.charAt(0);

    while (o!='q') {
        input = JOptionPane.showInputDialog("What is your first number? ");
        num1 = Double.parseDouble(input);
        input = JOptionPane.showInputDialog("What is your second number? ");
        num2 = Double.parseDouble(input);

        if (o == '/') {
            result = num1 / num2;
        } else if (o == '*') {
            result = num1 * num2;
        } else if (o == '+') {
            result = num1 + num2;
        } else if (o == '-') {
            result = num1 - num2;
        } 
        JOptionPane.showMessageDialog(null ,"Your answer is : " + result);

        input = JOptionPane.showInputDialog("What is your operand? ");
        o = input.charAt(0);
    }

}

请注意,您的用户必须非常清醒,以避免拼写错误并收到NumberFormatException ...