我在让自定义方程求值器工作时遇到一些困难。我将从文本文件中读取的字符串(除了字符串单词之间没有空格)作为方程式传递给它,并传递给它链接到它们所代表的值的关键字映射。我已经测试过了,我的所有 map 都工作正常。下面是我尝试处理结果,无论它是整数还是字符串。这将是仅有的两种允许的条目类型。方程的每一边都可以有一个或两个元素,用加号或减号分隔。唯一允许计算两侧的三个运算符是 <、>、=。双方仅限于只能拥有关键字或只能拥有整数,因此您不能拥有诸如敏捷 + 1 = 力量 + 2 之类的东西。
当我尝试编译此类时,当前遇到的错误是“没有找到适合 parseint 的方法”“方法 Integer.parseInt(String,int) 不适用”。如果我没有弄错的话,因为我直接编译这个类而不是主类,它甚至不会有映射来进行这种判断调用。这是一个问题吗?我以这种方式编译是因为我一直遇到问题,重新编译主类没有重新编译次要类文件,从而导致问题。
任何示例方程式:dexterity>3 或背景=Ex Legionary
import java.lang.String;
import java.util.HashMap;
import java.util.Map;
public class Equation {
private String[] sides = new String[2];
private String[] rawEquation = new String[3];
private String[] parts = new String[2];
private String type;
private int[] tempInt = new int[2];
private int[] finalSide = new int[2];
private String[] finalStride = new String[2];
public boolean solve(String equation, Map gladMap) {
if (equation.indexOf("<") > -1) {
sides = equation.split("<");
rawEquation[1] = "<";
} else if (equation.indexOf(">") > -1) {
sides = equation.split(">");
rawEquation[1] = ">";
} else if (equation.indexOf("=") > -1) {
sides = equation.split("=");
rawEquation[1] = "=";
}
rawEquation[0] = sides[0];
rawEquation[2] = sides[1];
for (int d = 0; d < 2; d++) {
if (sides[d].indexOf("+") > -1) {
parts = rawEquation[0].split("\\+");
for (int a = 0; a < 2; a++) {
if (isInteger(parts[a])){
tempInt[a] = Integer.parseInt(parts[a]);
} else {
tempInt[a] = Integer.parseInt(gladMap.get(parts[a]));
}
}
finalSide[d] = tempInt[0]+tempInt[1];
type = "Int";
} else if (rawEquation[0].indexOf("-") > -1) {
parts = rawEquation[0].split("\\-");
for (int a = 0; a < 2; a++) {
if (isInteger(parts[a])){
tempInt[a] = Integer.parseInt(parts[a]);
} else {
tempInt[a] = Integer.parseInt(gladMap.get(parts[a]));
}
}
finalSide[d] = tempInt[0]-tempInt[1];
type = "Int";
} else {
if (isInteger(sides[0])){
finalSide[d] = Integer.parseInt(sides[0]);
} else {
if (isInteger(gladMap.get(sides[0]))) {
finalSide[d] = Integer.parseInt(gladMap.get(sides[0]));
type = "Int";
} else {
finalStride[d] = gladMap.get(sides[0]);
type = "Str";
}
}
}
}
if (rawEquation[1].equals("<")) {
if (type.equals("Int")) {
if (finalSide[0] < finalSide[1]) {
return true;
}
}
} else if (rawEquation[1].equals(">")) {
if (type.equals("Int")) {
if (finalSide[0] > finalSide[1]) {
return true;
}
}
} else {
if (type.equals("Int")) {
if (finalSide[0] == finalSide[1]) {
return true;
}
} else if (type.equals("Str")) {
if (finalStride[0].equals(finalStride[1])) {
return true;
}
}
}
return false;
}
public boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception NumberFormatException ) {
return false;
}
}
}
我尝试通过创建临时字符串变量将 Integer.parseInt() 与 happyMap.get(sides[0]) 分开,但它没有改变任何内容。任何帮助将不胜感激!
最佳答案
在这里,您传递的 map 不具有通用类型。因此, get() 将始终返回一个对象,这不是 parseInt() 方法的合适参数。
将方法签名更改为
公共(public) boolean 求解(字符串方程,Map
应该可以解决错误。
关于java - 自定义方程求解器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17089950/