我的解释器语言似乎无法识别“+”符号并返回错误。我的代码怎么出错了?

My interpreter language doesn't seem to recognise the "+" symbol and is returning errors. How have I gone wrong in my code?

我写了一个解释器,它以 String 作为指令集。该指令集声明了一组变量和 return 其中一个。一个示例指令集是:

A = 2
B = 8
C = A + B
C

这应该是 return 变量 c 并在控制台中打印 10。前提条件是左侧必须始终是字母,右侧只能包含一个数字或两个数字的加法,并且 return 语句必须始终是变量。

我写了下面的代码来做到这一点:

public class Interpreter2 {

public static int Scanner() {
    int returnStatement = 0;
    String num1;
    String num2;
    int sum = 0;
    ArrayList<String> variables = new ArrayList<String>();
    ArrayList<Integer> equals = new ArrayList<Integer>();
    //Input instruction set in the quotation marks below
    String input = "A = 2\n B = 8\n C = A + B\n C";
    String[] lines = input.split("\n"); //Split the instruction set by line

    for (String i : lines) {
        i = i.replaceAll("\s", "");
        if (i.contains("=")) {          //If the line has an equals, it is a variable declaration   
            String[] sides = i.split("="); //Split the variable declarations into variables and what they equal
            variables.add(sides[0]);

            if (sides[1].contains("\+")) { //If the equals side has an addition, check if it is a number or a variable. Convert variables to numbers and add them up
                String[] add = sides[1].split("\+"); 
                num1 = add[0];
                num2 = add[1];
                for (int j = 0; j < variables.size(); j++) {
                    if (variables.get(j).equals(num1)) {    
                        num1 = Integer.toString(equals.get(j));
                    }   
                } 
                for (int k = 0; k < variables.size(); k++) {
                    if (variables.get(k).equals(num2)) {    
                        num2 = Integer.toString(equals.get(k));
                    }
                }
                sum = Integer.parseInt(num1) + Integer.parseInt(num2);
                equals.add(sum);
            }else { //If the equals side has no addition, it is simply equals to the variable
                equals.add(Integer.parseInt(sides[1]));
            }

        }else { //If the line does not have an equals, it is a return statement
            for (int l = 0; l < variables.size(); l++) {
                if (variables.get(l).equals(i)) {   
                    returnStatement = equals.get(l);
                }
            }
        }

    }
     return returnStatement;
}


public static void main(String[] args) {
        System.out.println(Scanner());
    }
}

然而这给出了错误

Exception in thread "main" java.lang.NumberFormatException: For input string: "A+B"

这指向第 39 行:

else { 
     equals.add(Integer.parseInt(sides[1]));
     }

这让我觉得我的 if 语句发现行中是否有“+”符号没有正常工作。 谁能看到我错过了什么? 如有必要,我可以解释任何代码,这可能是一团糟。

问题是 String#contains 接受正则表达式。它接受 CharSequence 和:

Returns true if and only if this string contains the specified sequence of char values.

所以你不需要转义+。简单地做:

if (sides[1].contains("+"))