You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新手求助:如何简化计算器代码中重复冗长的if语句?

Simplifying Your Simple Calculator Code (Reduce Repetitive If Statements)

Hey there! As a new programmer, it’s totally normal to end up with repetitive if statements when you’re figuring things out. Let’s walk through some straightforward ways to clean up your calculator code—starting with the method approach you tried (we’ll fix that!) and a couple other simple tricks.

First: The Easy Fix – Extract Logic into a Method + Use Switch Statements

Your repetitive ifs are almost certainly checking which operator the user entered (+, -, *, /) and running the corresponding calculation. Let’s pull that calculation logic into a separate method, and use a switch statement instead of a long chain of if-else (it’s cleaner and easier to read!).

Step 1: Write a Reusable Calculation Method

This method will take your two numbers and the operator, handle the math, and return the result. We’ll add basic error handling too (like catching division by zero).

import static java.lang.System.*;
import static javax.swing.JOptionPane.*;
import static java.lang.Integer.*;

public class SimpleCalc {

    // Our new reusable calculation method
    private static int calculate(int num1, int num2, String operator) {
        switch(operator) {
            case "+":
                return num1 + num2;
            case "-":
                return num1 - num2;
            case "*":
                return num1 * num2;
            case "/":
                if (num2 == 0) {
                    throw new IllegalArgumentException("Oops! Can't divide by zero.");
                }
                return num1 / num2;
            default:
                throw new IllegalArgumentException("Invalid operator! Use +, -, *, or /.");
        }
    }

    public static void main(String[] args) {
        try {
            // Get user input (we kept your static imports since you're using them!)
            int num1 = parseInt(showInputDialog("Enter first number"));
            int num2 = parseInt(showInputDialog("Enter second number"));
            String operator = showInputDialog("Enter operator (+, -, *, /)");

            // Call our calculation method instead of writing all those ifs!
            int result = calculate(num1, num2, operator);
            showMessageDialog(null, "Result: " + result);
        } catch (NumberFormatException e) {
            // Handle if user enters non-numeric values
            showMessageDialog(null, "Please enter valid whole numbers!");
        } catch (IllegalArgumentException e) {
            // Handle invalid operators or division by zero
            showMessageDialog(null, e.getMessage());
        }
    }
}

Why This Works:

  • No more repetitive ifs: All the operator checking and math lives in one place.
  • Cleaner main method: Your main code only handles input/output and error catching, which is easier to follow.
  • Easy to extend: Want to add a modulo (%) operation later? Just add a new case "%" in the calculate method—no need to rewrite the whole logic chain.

Bonus: An Even Cleaner (But Still Simple) Option – Use Enums (Optional)

If you want to take things a step further (once you’re comfortable with methods), enums let you wrap each operator’s symbol and logic together. This is great for scalability if you ever want to add more features.

import static java.lang.System.*;
import static javax.swing.JOptionPane.*;
import static java.lang.Integer.*;

public class SimpleCalc {

    // Define an enum for each operator, with its own calculation logic
    private enum Operator {
        ADD("+") {
            @Override
            int apply(int num1, int num2) {
                return num1 + num2;
            }
        },
        SUBTRACT("-") {
            @Override
            int apply(int num1, int num2) {
                return num1 - num2;
            }
        },
        MULTIPLY("*") {
            @Override
            int apply(int num1, int num2) {
                return num1 * num2;
            }
        },
        DIVIDE("/") {
            @Override
            int apply(int num1, int num2) {
                if (num2 == 0) {
                    throw new IllegalArgumentException("Oops! Can't divide by zero.");
                }
                return num1 / num2;
            }
        };

        private final String symbol;

        Operator(String symbol) {
            this.symbol = symbol;
        }

        // Each operator must implement this method to do its math
        abstract int apply(int num1, int num2);

        // Find the right operator from the user's input symbol
        public static Operator fromSymbol(String symbol) {
            for (Operator op : values()) {
                if (op.symbol.equals(symbol)) {
                    return op;
                }
            }
            throw new IllegalArgumentException("Invalid operator! Use +, -, *, or /.");
        }
    }

    public static void main(String[] args) {
        try {
            int num1 = parseInt(showInputDialog("Enter first number"));
            int num2 = parseInt(showInputDialog("Enter second number"));
            String operatorSymbol = showInputDialog("Enter operator (+, -, *, /)");

            // Get the matching operator enum and run its calculation
            Operator operator = Operator.fromSymbol(operatorSymbol);
            int result = operator.apply(num1, num2);
            showMessageDialog(null, "Result: " + result);
        } catch (NumberFormatException e) {
            showMessageDialog(null, "Please enter valid whole numbers!");
        } catch (IllegalArgumentException e) {
            showMessageDialog(null, e.getMessage());
        }
    }
}

Why This Is Nice:

  • All operator logic is self-contained—each operator knows its own symbol and how to calculate.
  • Adding a new operator is as simple as adding a new enum value (no editing big switch blocks!).

Final Tips for You:

  • Start with the method + switch approach first—it’s the easiest to grasp as a new coder.
  • Always test edge cases (like division by zero or non-numeric input) to make your calculator more robust.
  • Don’t worry if enums feel a bit tricky right now—master the basics first, then come back to them later!

内容的提问来源于stack exchange,提问作者Brobo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:14:21