⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 testcalculator2.java

📁 Java the UML Way 书中所有源码
💻 JAVA
字号:
/*
 * TestCalculator2.java   E.L. 2001-08-10
 *
 */
import javax.swing.JOptionPane;
class TestCalculator2 {
  public static void main(String[] args) {
    
    /* Reading data */
    String number1Read = JOptionPane.showInputDialog("First number: ");
    String number2Read = JOptionPane.showInputDialog("Second number: ");
    double number1 = Double.parseDouble(number1Read);
    double number2 = Double.parseDouble(number2Read);
    String[] options = {"plus", "minus", "multiply", "divide"};
    int option = JOptionPane.showOptionDialog(null, "Choose operator", 
      "The four arithmetical operations", 0, JOptionPane.PLAIN_MESSAGE, 
      null, options, options[0]); 

    
    /* Calculating results */
    Calculator calcus = new Calculator(number1, number2);
    double calculatedAnswer = 0.0;
    char operator = ' ';  // uses this in the result string
    boolean ok = true;
    if (option == 0) {
      operator = '+';
      calculatedAnswer = calcus.calculateSum();
    } else if (option == 1) {
      calculatedAnswer = calcus.calculateDifference();
      operator = '-';      
    } else if (option == 2) {
      calculatedAnswer = calcus.calculateProduct();
      operator = '*';
    } else if (option == 3) { 
      operator = '/';
      if (number2 == 0.0) ok = false;  // we have to avoid division by zero
      else calculatedAnswer = calcus.calculateQuotient();
    } else { // Esc is typed, or the dialog is closed
      ok = false;
    }

    /* Printing the result */
    String result;
    if (ok) result = number1 + " " + operator + " " + number2 + " = " + calculatedAnswer;
    else result = "It is not possible to calculate a result.";
    JOptionPane.showMessageDialog(null, result);
    System.exit(0);
  }
}
/* Example Run:

First number: 12.5
Second number: 3.56
Choose the operation "multiply"
Result: 12.5 * 3.56 = 44.5

First number: 12.5
Second number: 0.0
Choose the operation "divide"
Result: It is not possible to calculate a result.
*/

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -