我编写了一个解释器,它将 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 = 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
语句判断该行中是否有"+"符号无法正常工作 . 任何人都可以看到我_32507可能是一个巨大的混乱 .
1 回答
问题是String#contains不接受正则表达式 . 它接受
CharSequence
和:所以你不需要逃避
+
. 简单地说: