如何将包含数学表达式的字符串转换为整数? [英] How to convert a string containing math expression into an integer?

查看:79
本文介绍了如何将包含数学表达式的字符串转换为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为问题数组,用于存储在问题中的String类型. 我想将questionArray[0]转换为int. 我已经使用以下语句来做到这一点.

I have an array named questions array for String type that stores in the questions. I want to convert the questionArray[0] to an int. I have used the following statement to do that.

int aa = Integer.parseInt(questionArray[0]);

但是当我实现此语句并运行应用程序时,出现错误消息:invalid int: "10-4". 注意,10-4可以是任何随机算术表达式,因为它是一个随机问题游戏.例如:9+110/5

But when I implement this statement and when I run the application I get an error saying : invalid int: "10-4". Note that the 10-4 can be any random arithmetic expression because its a random questions game. e.g.: 9+1, 10/5 etc.

推荐答案

"10-4"不是一个简单的整数,它是一个计算,因此将其解析为int将不会产生任何结果..

"10-4" is not a simple integer, it's a calculation, so parsing it to an int will yield no results..

您必须解析您的字符串.

You'll have to parse your string..

int aa = evaluteQuestion(questionArray[0]);

真正的魔力发生在这里:

And the actual magic happens here:

public static int evaluteQuestion(String question) {
    Scanner sc = new Scanner(question);

    // get the next number from the scanner
    int firstValue = Integer.parseInt(sc.findInLine("[0-9]*"));

    // get everything which follows and is not a number (might contain white spaces)
    String operator = sc.findInLine("[^0-9]*").trim();
    int secondValue = Integer.parseInt(sc.findInLine("[0-9]*"));
    switch (operator){
        case "+":
            return firstValue + secondValue;
        case "-":
            return firstValue - secondValue;
        case "/":
            return firstValue / secondValue;
        case "*":
            return firstValue * secondValue;
        case "%":
            return firstValue % secondValue;
        // todo: add additional operators as needed..
        default:
            throw new RuntimeException("unknown operator: "+operator);
    }
}

如果表达式中包含更多部分,则可能需要将上面的代码放入循环中.但是要注意操作顺序.如果您想为任何表达式实现适当的解析器,事情可能会有些麻烦

If you have more parts in your expressions, you might want to put the code above into a loop. watch out for order of operation though. Things might get a little hairy if you want to implement a proper parser for any expression

这篇关于如何将包含数学表达式的字符串转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆