/**
* 请注意不要修改包名、类名,否则将导致考试成绩失效
*/
public class JavaTest {
public final static String Digitals = new String("012345678");
public final static String Operators = new String("+-*/");
public final static String Seperators = new String(" ()$");
/**
* 输入的中缀表达式中存在语法错误
*/
public static class SyntaxErrorException extends Exception {
private static final long serialVersionUID = 9109750478481891787L;
public SyntaxErrorException() {
}
}
/**
* 请实现convert函数,将中缀表达式字符串infixNotation转换成逆波兰表达式字符串,
* 可以根据需要增加变量和函数,但是注意不要改变convert函数的原型
*
* @param infixNotation
* 中缀表达式字符串
* @return 逆波兰表达式字符串
*/
public String convert(String infixNotation) throws SyntaxErrorException {
//TODO: add your code here.
return new String("1 1 +");
}
public static void main(String[] args) {
try {
JavaTest c = new JavaTest();
if (args.length == 1) {
System.out.print(c.convert(args[0]));
}
} catch (SyntaxErrorException e) {
}
}
}
package testcase;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Formater {
final static Pattern ws1 = Pattern.compile("^\\s+|\\s+$");
final static Pattern ws2 = Pattern.compile("\\s+");
final static Pattern op = Pattern.compile("\\s*([\\+\\-\\*/])\\s*");
public static String normalize(String str) {
str = ws1.matcher(str).replaceAll("");
str = ws2.matcher(str).replaceAll(" ");
Matcher m = op.matcher(str);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1));
}
m.appendTail(sb);
return sb.toString();
}
public static void main(String[] args) {
String str = ws1.matcher("1 $").replaceAll("");
System.out.println(str);
}
}
package testcase;
import static org.junit.Assert.*;
import org.junit.Test;
import huawei.JavaTest;
public class JavaTestTest extends JavaTest {
@Test
public void test_Case1() throws SyntaxErrorException {
assertEquals(Formater.normalize(convert("1 + 1$")), "1 1+");
}
@Test
public void test_Case2() throws SyntaxErrorException {
assertEquals(Formater.normalize(convert("5 + ((1 + 2) * 4) - 3$")),
"5 1 2+4*+3-");
}
@Test(expected=SyntaxErrorException.class)
public void test_Case3() throws SyntaxErrorException {
convert("1++2$");
}
}