我编写了一个解释器,它将String
作为指令集。此指令集声明一组变量并返回其中一个变量。一个示例指令集是:
A = 2
B = 8
C = A + B
C
这应该返回变量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 = 2n B = 8n C = A + Bn 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
和:
当且仅当此字符串包含指定的字符值序列时返回true。
所以您不需要逃离+
。简单操作:
if (sides[1].contains("+"))