需要有关代码 java 效率的建议

Need advice on code java efficiency

我是 java 编程的新手,我刚刚创建了一个计算器程序,它似乎工作正常,但其他程序员似乎在他们的计算器程序中使用 "parsing a lot"。只是想问问我是否采取了错误的方法,并且将来使用这种 logic.Thanks.

可能 运行 会遇到问题
class Refresh {

private final String a;
private final String b;
private final String c;
private final String d;
private double x, y;

public Refresh() {
    a = "Enter the first number: ";
    b = "Enter the function; ";
    c = "Enter the second number: ";
    d = "The result is: ";
}

public void types() {
    Scanner typ = new Scanner(System.in);

    try {
        System.out.println(a);
        x = typ.nextDouble();
    } catch (InputMismatchException e) {
        System.out.println("Please use only numbers!");
        System.exit(1);
    }
    System.out.println(b);
    String func = typ.next();

    try {
        System.out.println(c);
        y = typ.nextDouble();
    } catch (InputMismatchException e) {
        System.out.println("Please use only numbers!");
        System.exit(1);
    }

    switch (func) {

        case "+":
            System.out.println(d + (x + y));
            break;

        case "-":
            System.out.println(d + (x - y));
            break;
        case "/":
            if (y == 0) {

                System.out.println("Cannot divide by zero!");
            } else {
                System.out.println(d + (x / y));
            }
            break;
        case "*":
            System.out.println(d + (x * y));
            break;

        default:
            System.out.println(func + " is not valid function");
    }
}

    public static void main(String[] args) {
        Refresh fin = new Refresh();
        fin.types();
    }
}

解析就是扫描一组字符,然后将它们分成自己的结构(将它们标记化)。

String aStr = "10";

变量 aStr 的类型为 String。然后您可以解析该字符串。

int aInt = Integer.parseInt(aStr);

仅供参考,Java 有一个内置的计算器库。

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
String result = "100/10";
System.out.println(scriptEngine.eval(result));

好吧,这实际上是一个非常基本的例子。老实说,你做得很好。甚至更擅长在这个时候问这个问题。通常人们在学习过程中忽略了效率而为时已晚。

他们为什么要解析?

如果您不了解以下内容,那么您可能应该尝试 reading 更多内容。

扫描仪读取用户的所有按键输入。让我们举个例子

输入一个数字> 12

扫描器将保留 12\n

现在你看到了吗?扫描器只保留数字,它实际上保留一个字符串。其中包含 12\n

当您询问扫描仪 nextDouble 时,它只会给您 12

但它仍然坚持 \n 所以下一个字符串输入,字符串 \n 将被分配。

通过解析,您将忽略此问题。而且您将更好地控制用户输入。

您的程序可以作为演示或学习的一个步骤 Java,但您可能不会将其用作生产程序。原因是您的代码采用命令行界面 (static void main(), Scanner, System.out.println()).

现在用户已经习惯了图形化的解决方案。他们希望输入和输出在图形前端给出,计算应该在单独的逻辑中完成。

按照这种观点,我会将您的程序分为 3 个部分:

  • 进行计算的后端class(以下示例代码中的计算器class)
  • 前端 class(以下称为 SimpleFrontEnd),它基于您的代码构建,但稍后可以替换为例如网络界面
  • 后端和前端之间通信的数据对象(下面的计算class从前端向后端发送信息)

有了这3个部分,你可以独立修改它们。您可以决定在前端只输入一个字符串,然后在发送到后端之前对其进行解析。

我可能不会在需要解析的前端使用单个字符串,而是使用直接映射到下面计算 class 的 JSON 对象,原因如下:前端可以轻松地修改彼此独立的JSON对象的操作数和运算符,而修改必须解析的字符串则更为复杂。

这是将前端与后端分开的示例代码:

public class Calculation {
    private double leftOperand;
    private String operator;
    private double rightOperand;

    public double getLeftOperand() {
        return leftOperand;
    }

    public void setLeftOperand(double leftOperand) {
        this.leftOperand = leftOperand;
    }

    public String getOperator() {
        return operator;
    }

    public void setOperator(String operator) {
        this.operator = operator;
    }

    public double getRightOperand() {
        return rightOperand;
    }

    public void setRightOperand(double rightOperand) {
        this.rightOperand = rightOperand;
    }
}

public class Calculator {
    public double calculate(Calculation calculation) {
        switch (calculation.getOperator()) {
            case "+":
                return calculation.getLeftOperand() + calculation.getRightOperand();
            case "-":
                return calculation.getLeftOperand() - calculation.getRightOperand();
            case "/":
                if (calculation.getRightOperand() == 0) {
                    throw new IllegalArgumentException("Cannot divide by zero!");
                }
                return calculation.getLeftOperand() / calculation.getRightOperand();
            case "*":
                return calculation.getLeftOperand() * calculation.getRightOperand();
            default:
                throw new IllegalArgumentException(String.format("%s is not valid function", calculation.getOperator()));
        }
    }
}

public class SimpleFrontEnd {
    public static void main(String[] args) {
        try {
            //1. input, could be later replaced with a front end
            Scanner typ = new Scanner(System.in);
            System.out.println("Enter the first number: ");
            double x = typ.nextDouble();
            System.out.println("Enter the function: ");
            String func = typ.next();
            System.out.println("Enter the second number: ");
            double y = typ.nextDouble();

            //2. store input in an data object that will be sent to the back end (later on, a web interface could send this as a JSON)
            Calculation calculation = new Calculation();
            calculation.setLeftOperand(x);
            calculation.setOperator(func);
            calculation.setRightOperand(y);

            //3. retrieve the result from the back end
            Calculator calculator = new Calculator();
            try {
                double result = calculator.calculate(calculation);
                System.out.println(String.format("The result is: %f", result));
            } catch (IllegalArgumentException e) {
                System.out.println(e.getMessage());
            }
        } catch (InputMismatchException e) {
            System.out.println("Please use only numbers!");
        }
    }
}