24h購物| | PChome| 登入
2012-05-15 06:54:51| 人氣2,951| 回應0 | 上一篇 | 下一篇

[JAVA][作業][Lab6] Exception Handling

推薦 0 收藏 0 轉貼0 訂閱站台

Write a program that can serve as a simple calculator. This calculator keeps track of a single number (of type double) that is called result and that starts out as 0.0. Each cycle allows the user to repeatedly add, subtract, multiply, or divide by a second number. The result of one of these operations becomes the new value of result. The calculation ends when the user enters the letter R for “result” (either in uppercase or lowercase). The user is allowed to do another calculation from the beginning as often as he or she wants. Use the scanf for input.

The input format is shown in the following sample dialog. If the user enters any operator symbol other than +, −, *, or /, then display message UnknownOperatorException is thrown and the user is asked to reenter that line of input. Defining the class UnknownOperatorException is part of this project.

Calculator is on.
result = 0.0
+5
result + 5.0 = 5.0
result = 5.0
*2.2
result * 2.2 = 11.0
result = 11.0
% 10
% is an unknown operation
Reenter, your last line:
* 0.1
result * 0.1 = 1.1
result = 1.1
r
Final result = 1.1
Again? (y/n)
yes
result = 0.0
+10
result + 10.0 = 10.0
new result = 10.0
/2
result / 2.0 = 5.0
updated result = 5.0
r
Final result = 5.0
Again? (y/n)
N
End of Program


import MyException.*;
import java.util.Scanner;

/**
 * @author Shiang-Yun Yang
 */
public class Calculator {
    public static Scanner keyboard = new Scanner(System.in);
    public static String cmd;

    /*
     * All process will do on the same String(cmd).
     */
    public static void run() {
        boolean first;
        char operator;
        double result, number;
        System.out.println("Calculator is on.");
        do {
            result = 0.0;
            first = true;
            System.out.println("result = " + result);
            while (true) {
                cmd = keyboard.nextLine();
                cmd = cmd.trim();
                cmd = cmd.toLowerCase();
                if (cmd.equals("r"))
                    break;
                try {
                    operator = getOperator();
                    number = getNumber();
                    switch (operator) {
                    case '+':
                        result += number;
                        break;
                    case '-':
                        result -= number;
                        break;
                    case '*':
                        result *= number;
                        break;
                    case '/':
                        if (number == 0)
                            throw new Exception("Divide by zero.");
                        result /= number;
                        break;
                    default:
                        throw new UnknownOperatorException(operator);
                    }
                    System.out.printf("result %c %g = %g\n", operator, number, result);
                    if (first)
                        System.out.println("new result = " + result);
                    else
                        System.out.println("update result = " + result);
                    first = false;
                } catch (UnknownOperatorException e) {
                    System.out.printf("%c is an unknown operation.\n", e.operator);
                    System.out.println("Reenter, your last line:");
                } catch (NumberFormatException e) {
                    System.out.println("Format Error: Not Find Number.");
                    System.out.println("Reenter, your last line:");
                } catch (Exception e) {
                    System.out.println("Format Error: " + e.getMessage());
                    System.out.println("Reenter, your last line:");
                }
            }
            System.out.println("Final result = " + result);
        } while (checkAgain() == true);
        System.out.println("End of Program");
    }

    /*
     * Use String.trim() to get the first character which is not a whitespace.
     * The first character will be an operator.
     */
    public static char getOperator() throws Exception {
        cmd = cmd.trim();
        if (!Character.isDigit(cmd.charAt(0))) {
            char operator = cmd.charAt(0);
            cmd = cmd.substring(1);
            return operator;
        }
        throw new Exception("Not Find Operator");
    }

    /*
     * Method to process Exception
     * 1. Use Regular expression to check Format correct.
     *     if (!(cmd.matches("[+||-]{0,1}[0-9]+")
     *         || cmd.matches("[+||-]{0,1}[0-9]*[.][0-9]+")))
     * 2. Double.parseDouble will throw NumberFormatException.
     */
    public static double getNumber() {
        return Double.parseDouble(cmd);
    }

    public static boolean checkAgain() {
        while (true) {
            System.out.println("Again? (y/n)");
            cmd = keyboard.nextLine();
            cmd = cmd.toLowerCase();
            if (cmd.equals("y") || cmd.equals("yes"))
                return true;
            if (cmd.equals("n") || cmd.equals("no"))
                return false;
            System.out.println("You should make a decision.");
        }
    }

    public static void main(String[] args) {
        Calculator.run();
    }
}


package MyException;

public class UnknownOperatorException extends Exception {
    public char operator;
    public UnknownOperatorException(char operator) {
        super();
        this.operator = operator;
    }
    public UnknownOperatorException(String msg, char operator) {
        super(msg);
        this.operator = operator;
    }
}


台長: Morris
人氣(2,951) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: [學習]Java |
此分類下一篇:[JAVA] Exception 例外處理實驗
此分類上一篇:[JAVA][作業][被拋棄的 Lab5]

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文