用Java中的字符数组执行数学运算的最有效方法是什么?

问题描述

我是一个初学者-我应该写一个类,该类在char数组中计算给定数学表达式的结果,并考虑到运算符+,-,*和/的优先级。例如:

输入:char [] a = {'1','1','1','-','1','2','*','2'},输出:87

我能想到的所有解决方案都涉及if语句或混乱的嵌套循环。有什么建议吗?在此先感谢您的帮助。 顺便说一下,这就是我到目前为止所拥有的:

import java.util.Scanner;

public class MathInCharArray {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        System.out.print("Input a calculation without spaces,using the operators +,-,*,or /: ");
        String userInput = scnr.next();
        char[] equationArray = new char[userInput.length()];
        boolean operator = false;

        for (int i = 0; i < userInput.length() - 1; ++i) {
            equationArray[i] = userInput.charAt(i);
        }

        for (int i = 1; i < userInput.length() - 1; ++i) {
            for (int j = 0; j < userInput.length() - 2; ++j) {
                
            }
        }

    }
}

解决方法

您可以尝试将两个数字连接到一个字符串变量中,将运算符存储到一个单独的变量中,然后对您的运算符使用switch语句。在计算表达式时,您可以从那里将数字转换为双精度数字。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...