Java 如何将包含数学表达式的字符串转换为整数?

Java 如何将包含数学表达式的字符串转换为整数?,java,string,parsing,symbolic-math,Java,String,Parsing,Symbolic Math,我有一个名为questions array的数组,用于存储在questions中的String类型。 我想将questionArray[0]转换为int。 我使用了以下语句来实现这一点 int aa = Integer.parseInt(questionArray[0]); 但是,当我实现这条语句并运行应用程序时,我会收到一个错误消息:invalid int:“10-4”。 请注意,10-4可以是任何随机算术表达式,因为它是一个随机问题游戏。e、 g.:9+1,10/5等等。这比仅仅解析一个字

我有一个名为questions array的数组,用于存储在questions中的
String
类型。 我想将
questionArray[0]
转换为
int
。 我使用了以下语句来实现这一点

int aa = Integer.parseInt(questionArray[0]);
但是,当我实现这条语句并运行应用程序时,我会收到一个错误消息:
invalid int:“10-4”

请注意,
10-4
可以是任何随机算术表达式,因为它是一个随机问题游戏。e、 g.:
9+1
10/5
等等。

这比仅仅解析一个
字符串有点复杂,因为它有一个算术符号,可以是任何东西。所以,让我们一步一步地看一下:

//Lets say you have a string like this
questionArray[0] = "10+4";
//Lets find the Arithmetic sign first in the String
String sign = null;

Pattern regex = Pattern.compile("[+*/]|(?<=\\s)-");
Matcher matcher = regex.matcher(questionArray[0]);
    while(matcher.find()) {
       sign = matcher.group().trim();  //Store that Arithmetic sign here.       
    }

String [] parts = questionArray[0].split("[+*/]|(?<=\\s)-"); //Now break up the string using this regex. 
                                              //This regex will find whatever Arithmetic sign 
                                              //there is inside this String and store the result 
                                              //in parts array.

int firstNumber = Integer.parseInt(parts[0]); //The first number in the String
int secondNumber = Integer.parseInt(parts[1]);//The second number in the String

//a simple if-else statements that will help us find the final answer.
int result = 0;
if (sign.equals("+")){
    result = firstNumber + secondNumber;
} else if (sign.equals("-")) {
    result = firstNumber - secondNumber;
} else if(sign.equals("*")) {    
    result = firstNumber * secondNumber;
} else if (sign.equals("/")){
    result = firstNumber / secondNumber;
} else {
    System.out.println("unknown operation");
}

System.out.println(result);
//假设您有这样一个字符串
问题数组[0]=“10+4”;
//让我们先在字符串中找到算术符号
字符串符号=null;
Pattern regex=Pattern.compile(“[+*/]|”(?
“10-4”
不是一个简单的整数,它是一个计算,因此将其解析为
int
将不会产生任何结果

你必须解析你的字符串

int aa = evaluteQuestion(questionArray[0]);
而真正的魔法发生在这里:

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);
    }
}

如果表达式中有更多部分,则可能需要将上面的代码放入循环中。但请注意操作顺序。如果要为任何表达式实现适当的解析器,则可能会有点麻烦,如果我正确理解questionArray[0]等于“10-4"这是一个包含非数字字符的字符串,这里是“-”字符。如果我没记错的话,ParseInt只能处理数字,而不能处理表达式。你必须编写一个函数,从字符串中提取第一个和第二个数字,然后根据中间的运算符进行计算。我删除了我的答案,现在正在处理新的问题。抓紧点。为什么这个问题的分数这么低?它遵循了所有提出好问题的规则,问题很明显。伙计们,不要只是否决投票,至少留下一条评论…@FarazDurrani如果它的/,*或+?@Faraz Durrani不需要粗鲁!+你有4个
如果
条件,这是相互排斥。但是所有4个都会被执行。如果
s,可能你的代码会受益于一些其他的
。或者甚至可能是一个
开关盒
?@FarazDurrani:我仍然没有否决,所以我没有什么可以收回的。你需要使
int result=0;
。否则,编译器会显示一个错误。好了,修复它;)@Hackerdarshi不,这不是必需的,因为程序在初始化之前不会返回结果。修复仍然是值得的,因为它现在是更好的代码,imho。@Tom不,他是对的。最初我没有默认的大小写。但是变量现在已经过时了。啊,好的。没有注意到他的注释比用t编辑的要旧他
default
case:)。