我正在编写一个程序来解决后缀问题。我不需要算法方面的帮助,因为我已经知道了。但是我偶然发现了替换所有功能的问题在这个程序中,我们给出了应该定义的运算符;我将定义存储在地图中。E 表示这个问题是一个评估,D 表示这个问题是一个定义。定义可以相互嵌套。当我尝试使用 replaceAll 函数检索定义时,我的问题就出现了。除了在一个实例上之外,它都可以工作。我将给出输入文件和我的输出来说明我的意思。
import java.io.*;
import java.util.*;
class Problem
{
private static String line;
private static HashMap<String, String> map = new HashMap();
private static Stack operandStack = new Stack();
public static void main(String[] args) throws IOException
{
FileReader fin = new FileReader("postfix.in");
BufferedReader infile = new BufferedReader(fin);
FileWriter fout = new FileWriter("postfix.out");
BufferedWriter outfile = new BufferedWriter(fout);
line = infile.readLine();
do
{
if(line.substring(0,1).equals("E"))
{
line = line.replaceAll("E", "");
line = line.replaceAll("\"+", "");
for(int i = 0; i < line.length(); i++)
{
if(map.containsKey(line.substring(i,i+1)) ||
line.substring(i, i+1).matches("!|-|!|%|/"))
{
//check to see if its not a predifined operator
if(!line.substring(i, i+1).matches("!|-|!|%|/"))
{
String operator;
operator = line.substring(i, i+1);
//simplifies operators
line = line.replaceAll("\\"+operator, map.get(operator));
}
}
else if(!line.substring(i,i+1).equals(" "))
{
operandStack.push(line.substring(i,i+1));
}
}
System.out.println(line);
operandStack.clear();
}
else if(line.substring(0,1).equals("D"))
{
line = line.replaceAll("\"$", ""); //remove quote at end of string
map.put(line.substring(1,2), line.substring(3)); //put the definition on the map
}
// System.out.println(map);
line = infile.readLine();
}while(!line.equals("Q"));
infile.close();
outfile.close();
}
}
这是输入文件
D+" 0%--"
E"1 2+"
D*" 1%//"
E"3 4*"
D@"!!**"
E"17 4@+6*5/"
D&"!*"
D$" 1%/"
Da"$/"
D'" 0%-"
E"28 5&'-$"
E"3 4$/"
E"3 4a"
E"4 5a3/"
E"4@&"
E"4&@"
E"2!!!!****@"
E"2&&&@"
Q
代码的输出
1 2 0%--
3 4 1%//
17 4!! 1%// 1%// 0%--6 1%//5/
28 5! 1%// 0%-- 1%/
3 4 1%//
3 4a //this is not simplified
4 5a3/ //this is not simpliied
4!! 1%// 1%//! 1%//
4! 1%//!! 1%// 1%//
2!!!! 1%// 1%// 1%// 1%//!! 1%// 1%//
2! 1%//! 1%//! 1%//!! 1%// 1%//
我相信这个问题的解决方案在于修复这条线,但我不知道该怎么做。
line = line.replaceAll("\\"+operator, map.get(operator));