gpt4 book ai didi

Java 替换全部问题

转载 作者:行者123 更新时间:2023-12-01 16:00:15 24 4
gpt4 key购买 nike

我正在编写一个程序来解决后缀问题。我不需要算法方面的帮助,因为我已经知道了。但我偶然发现了替换所有功能的问题在这个程序中,我们给出了应该定义的运算符;我将定义存储在 map 中。 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));

最佳答案

看看这是否有效。替换您关心的行:

line = line.replaceAll("\\"+operator, map.get(operator));

具有以下内容:

line = line.replaceAll(
Pattern.quote(operator),
Matcher.quoteReplacement(map.get(operator)));

它产生输出:

1 2 0%--
3 4 1%//
17 4!! 1%// 1%// 0%--6 1%//5/
28 5! 1%// 0%-- 1%/
3 4 1%//
3 4$/
4 5$/3/
4!! 1%// 1%//! 1%//
4! 1%//!! 1%// 1%//
2!!!! 1%// 1%// 1%// 1%//!! 1%// 1%//
2! 1%//! 1%//! 1%//!! 1%// 1%//

这看起来不错,但我没有广泛查看它是否正确。

关于Java 替换全部问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4161829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com