如何从左到右计算表达式

时间:2016-02-06 15:06:09

标签: java android

我目前正在创建一个数学测验游戏,向用户输出随机算术问题。我有一个函数,它创建问题并将它们存储在字符串数组中。问题可以在问题中存在的整数数量上有所不同;例如一个问题可以是3 + 4-9 / 3 =或4 * 2/9 =但是必须存在的最小整数是2。 3 + 4 =等。

我要做的是评估从左到右阅读的问题忽略操作的顺序。例如。 4 + 2 * 5 =应该等于30而不是14。

我对这个问题的看法是:

获取问题,遍历字符串并提取单个字符并将其存储在arraylist中。将这些字符转换为int并首先计算arraylist中的前三个elemtns,将答案存储在临时int值中。获取接下来的2个元素并检查它是否不包含等号,如果它没有用这两个元素计算临时int值。继续这样做,虽然它没有找到一个等号。如果找到等号,则停止迭代并产生结果。

我的问题是我似乎无法将操作+, - ,*,/转换为int值。我想我可以将每个字符转换为int。

public void initAnswers(){
   for(int i =0; i < questions.length; i++){
       ArrayList<Integer> indivialIntegers = new ArrayList<>();
       String questionToGetIndividual = questions[0];
       //extracting individual chars
       for(int j = 0; j < questionToGetIndividual.length(); j++){
           indivialIntegers.add(Character.getNumericValue(questionToGetIndividual.charAt(j)));
       }
   }

EDIT =这是我更新的代码。我收到一个数字格式异常错误。 引起:java.lang.NumberFormatException:无效的int

有人能看出原因吗?顺便说一句,我写了一个方法来生成问题(问题中的整数量是随机生成的)。它们存储在一个数组中。我只是简单地遍历该数组中的每个问题并评估答案:我的启动函数是initAnswers()。

public int computeAnswerThreeTerms(int numberOne, int numberTwo, String operation){
   if(operation.equals("+")){
       Log.d("onc","in addition");
       return numberOne + numberTwo;
   }else if(operation.equals("-")){
       Log.d("onc","in subtraction");
       return numberOne - numberTwo;
   }else if(operation.equals("/")){
       Log.d("onc","in division");
       return numberOne / numberTwo;
   }else if(operation.equals("*")){
       Log.d("onc","in multiplication");
       return numberOne * numberTwo;
   }else{
       return 0;
   }
}

public int computeAnswer(int numberOne, String operation, int runningTotal){

    if(operation.equals("+")){
        Log.d("onc","in addition");
        return numberOne + runningTotal;
    }else if(operation.equals("-")){
        Log.d("onc","in subtraction");
        return numberOne - runningTotal;
    }else if(operation.equals("/")){
        Log.d("onc","in division");
        return numberOne / runningTotal;
    }else if(operation.equals("*")){
        Log.d("onc","in multiplication");
        return numberOne * runningTotal;
    }else{
        return 0;
    }
}

public void getAnswer(ArrayList<String> toBeExamined){
    //get numbers and put them in an array
    //get operations and put them in an array
    for(int i =0; i < toBeExamined.size(); i++){
        String extractingIntegers = toBeExamined.get(i);
        // /d matches digits /D matches non digits
        String[] numbersInStringformat = extractingIntegers.split("/d");
        ArrayList<Integer> numbersInNumberformat = new ArrayList<>();
        for(int counter = 0; counter < numbersInStringformat.length; counter++){
            numbersInNumberformat.add(Integer.parseInt(numbersInStringformat[counter]));
        }
        String[] operationsInStringformat = extractingIntegers.split("/D");

        int tempAnswer;
        int tempIntCounter =0;
        int stringCounter =0;
        tempAnswer = computeAnswerThreeTerms(numbersInNumberformat.get(tempIntCounter), numbersInNumberformat.get(tempIntCounter+1), operationsInStringformat[stringCounter]);
        tempIntCounter = 1;
        while(!operationsInStringformat[1].equals("=")){
            if(operationsInStringformat[stringCounter].equals("=")){
                break;
            }
            tempAnswer = computeAnswer(numbersInNumberformat.get(tempIntCounter++),operationsInStringformat[stringCounter],tempAnswer);
        }
        answers[i] = tempAnswer;

    }
}

public void initAnswers(){
    ArrayList<String> individualCharacters = new ArrayList<>();

    for(int i =0; i < questions.length; i++){
        //change i to 0 for testing purposes
       String questionToGetIndividual = questions[i];
       //extracting individual chars
       individualCharacters.add(questionToGetIndividual);
    }
    getAnswer(individualCharacters);
}

2 个答案:

答案 0 :(得分:0)

你基本上需要做的是:

  • 从您的问题中解析int[]个操作数(假设n个项目);
  • 解析运算符Operator[](+ - / *)。这是n-1个项目。 Operator是一个简单的enum,其转换器从char到价值&amp;将Operator应用于2个操作数的函数;
  • 循环通过将它们应用于当前值和运算符的运算符数组。操作数;

Aslo,请检查此问题:What's a good library for parsing mathematical expressions in java?

答案 1 :(得分:0)

你去吧

String question = "11+2*3=";
        int first = Integer.MAX_VALUE;
        int second = 0;
        int result = 0;
        boolean firstNumber = true;
        String operator = "";
        String number = "";

    for(char c : question.toCharArray()) {
        if(c != '+' && c != '-' && c != '*' && c != '/' && c != '=') {
            number += c;
        } else {
            if(firstNumber) {
                first = Integer.parseInt(number);
                firstNumber = false;
                operator += c;
                number = "";
                result = first;
            } else {
                second = Integer.parseInt(number);
                //firstNumber = true;
                switch(operator) {
                case "+":
                    result = result + second;
                    break;
                case "-":
                    result = result - second;
                    break;
                case "*":
                    result = result * second;
                    break;
                case "/":
                    result = result / second;
                    break;
                }
                number = "";
                operator = "";
                operator += c;
                if(operator.equals("=")) {
                    System.out.println(result);
                    return;
                }
            }
        }
    }