【问题标题】:recursive parsing calculator java递归解析计算器java
【发布时间】:2018-12-07 03:38:18
【问题描述】:

我正在尝试在 Java 中创建一个用于加法、乘法和阶乘的递归解析计算器,但我正在努力阅读用户输入以将输入拆分为数字和运算符的第一部分。在调试时,我试图查看哪里出了问题,我发现当“+”通过 if else 语句时,它只是跳过了它。我真的不确定问题是什么,我最初尝试使用标记,然后拆分为子字符串,但当时也不太顺利。任何帮助,将不胜感激。谢谢

package com.company;
import java.util.Scanner;

class Main {

    public static void main(String[] param) {
        String input = input("Please enter an expression");
        int n = input.length()-1;
        String[] splitter = input.split("(?<=\\G.)");
        split(input, n);
        //int result = calculate(input);
        //String[] splitter = input.split("(?<=\\G.)");
    }
    public static String split(String input, int n) {
        String[] splitter = input.split("(?<=\\G.)");
        System.out.println(splitter[n]);
        String symbol = splitter[n];
        if (symbol.equals("+")) {
            evalADD(n, splitter);
        }
        if (symbol.equals("*")) {
            evalMULT(n, splitter);
        }
        if (symbol.equals("!")) {
            evalFACT(n, splitter);
        }
        else if (Integer.parseInt(splitter[n]) >= 0 && Integer.parseInt(splitter[n]) <=9)
        {
            if (n != 0) {
                n = n - 1;
                split(input, n);
            }
        }

        if (n != 0)
            n = n - 1;
        split(input, n);
        return input;
    }
    public static int evalADD(int n, String [] splitter){
        int arg1;
        int arg2;
        int result;
        arg1 = Integer.parseInt(splitter[n+1]);
        arg2 = Integer.parseInt(splitter[n+2]);
        result = arg1 + arg2;
        return result;
    }
    public static int evalMULT(int n, String [] splitter){
        int arg1;
        int arg2;
        int result;
        arg1 = Integer.parseInt(splitter[n+1]);
        arg2 = Integer.parseInt(splitter[n+2]);
        result = arg1 * arg2;
        return result;
    }
    public static int evalFACT(int n, String [] splitter){
        int arg1;
        int arg2;
        int result;
        arg1 = Integer.parseInt(splitter[n+1]);
        arg2 = Integer.parseInt(splitter[n+2]);
        result = arg1 - arg2;
        return result;
    }
    public static String input(String message) {
        Scanner scanner = new Scanner(System.in);
        System.out.println(message);
        return (scanner.nextLine());
    }
}

【问题讨论】:

    标签: java parsing recursion calculator procedural-programming


    【解决方案1】:

    我注意到您使用的是java.util.Scanner。我编写了一个脚本,应该按照您的所有标准为您完成任务:

    import java.util.Scanner;
    
    class recursiveParsingCalculator {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            // Ask user to input the expression
            System.out.println("Please input the expression");
            String userInput = scanner.nextLine();
            System.out.println(
                    "And the final result is: " + recursiveCalculation(userInput, userInput.length() - 1, 0, 0, 0));
            scanner.close();
            System.exit(0);
        }
    
        // Identify the type of character at a specific position
        public static char charOfString(String userInput, int i) {
            return userInput.charAt(i);
        }
    
        /*
         * Position must be userInput.length() - 1 initially. currentResults, operand1
         * and operand2 are also meant to be initilized with 0.
         */
        public static int recursiveCalculation(String userInput, int position, int operand1, int operand2,
                int currentResults) {
            // If position is zero, just output the operand.
            if (position == 0) {
                if (Character.isDigit(charOfString(userInput, position))) {
                    return charOfString(userInput, position) - '0';
                } else {
                    System.out.println("Invalid input.");
                }
            }
            if (position > -1) {
                // Check if it is a number or an operator
                if (Character.isDigit(charOfString(userInput, position))) {
                    operand1 = charOfString(userInput, position) - '0'; // First operand
    
                    // Check if 2nd char is a number or an operator.
                    if (Character.isDigit(charOfString(userInput, position - 1))) {
                        operand2 = charOfString(userInput, position - 1) - '0';
                        position = position - 1;
                    }
                } else {
                    // If it is an operator, then proceed to compute the results so far
                    char operator = charOfString(userInput, position);
    
                    // If it is a binary situation
                    if (operator == '+' || operator == '*') {
                        currentResults = binaryOperator(operator, operand1, operand2);
                        operand2 = currentResults;
                    }
                    // If it is an unary situation
                    else if (operator == '!') {
                        if (currentResults == 0) {
                            currentResults = operand1;
                        }
                        currentResults = unaryOperator(currentResults);
                        operand2 = currentResults;
                    } else {
                        System.out.println("Invalid operator");
                        return 0; // Return zero by default
                    }
                }
                position = position - 1;
            }
            if (position > -1) {
                return recursiveCalculation(userInput, position, operand1, operand2, currentResults);
            } else {
                return currentResults;
            }
        }
    
        public static int binaryOperator(char operator, int operand1, int operand2) {
            switch (operator) {
            case '+':
                return operand1 + operand2;
            case '*':
                return operand1 * operand2;
            default:
                System.out.println("Invalid binary Operator");
                return 0; // Return zero by default
            }
        }
    
        // Calculate the factorial
        public static int unaryOperator(int operand) {
            if (operand <= 1)
                return 1;
            else
                return operand * unaryOperator(operand - 1);
        }
    }
    

    使用示例:对于二元运算符,输入+21,它会为您添加它们。对于一元,输入 !3,它将产生阶乘。现在,您可以使用一元和二元运算符尝试任何数字组合和排列链,它会递归地为您计算值。

    例如,考虑输入 !*3+12:它将添加 12,然后将其乘以 3 最后,它从整个表达式中计算出阶乘,从而得到预期的362880

    【讨论】:

      【解决方案2】:

      为什么不把输入的计算字符串赋值给一个字符数组,遍历数组,匹配字符'+'、'-'、'*'?

      【讨论】:

      • 谢谢,我会试一试,我的作业说不要使用显式 for 循环,但我认为我的教授不希望在实际计算中使用循环,我会尝试看看循环是否只允许检查操作员
      • 如果它至少有帮助,为什么不提供一个upvode
      猜你喜欢
      • 2019-09-08
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      • 2014-04-14
      • 1970-01-01
      • 2016-10-17
      • 1970-01-01
      • 2021-01-07
      相关资源
      最近更新 更多