⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 intopost.java

📁 DO-WHILE循环语句的翻译程序设计(LL(1)法、输出三地址表示)
💻 JAVA
字号:
class InToPost { // infix to postfix,从中缀表达式转换到后缀表达式的类,即输出中间代码的类
	private YStack theStack;//再该方法中,没有把“=”考虑为操作符,所以后缀表达式中的“=”依然在前面
							

	private String input;

	private String output = "";

	public InToPost(String input) {//转换的构造方法
		this.input = input;
		int stackSize = input.length();
		theStack = new YStack(stackSize);
	}

	public String Translate() {//转换的主要方法,主要利用了栈的数据结构

		for (int j = 0; j < input.length(); j++) {
			char ch = input.charAt(j);//按顺序取出输入串的每个字符

			switch (ch) {
			case '+'://如果是“+”或“-”号,则调用got方法,并把1赋值进去
			case '-':
				got(ch, 1);
				break;
			case '*'://如果是“*”或“/”号,则调用got方法,并把2赋值进去
			case '/':
				got(ch, 2);
				break;
			case '('://遇到左括号则进栈
				theStack.push(ch);
				break;
			case ')'://遇到右括号,则调用gotParten()方法
				gotParen(ch);
				break;
			/*
			 * case '=': break;
			 */
			case '#'://如果是“#”或“;”号,则不做任何操作
				break;
			case ';':
				break;
			default://否则取出的都是数据,则把他们当作一个整体输出
				output = output + ch;
				break;
			}
		}
		while (!theStack.isEmpty()) {//如果栈不空的话,则把栈顶元素输出
			output = output + theStack.pop();
		}

		return output;

	}

	public void got(char op, int i) {
		while (!theStack.isEmpty()) {
			char opTop = theStack.pop();//取栈顶元素
			int j;
			if (opTop == '(') {//遇到左括号,则进栈
				theStack.push(opTop);
				break;
			} else if (opTop == '+' || opTop == '-')//如果是“+”和“-”号,则将j设为1,即设置其优先级为1
				j = 1;
			else//如果是“*”和“/”号,则将j设为2,即设置其优先级为2,其余的符号默认优先级为0
				j = 2;
			if (j < i) {//如果栈中元素的优先级较小,则将取出的元素再进栈
				theStack.push(opTop);
				break;
			} else//否则出栈输出
				output = output + opTop;
		}

		theStack.push(op);
	}

	public void gotParen(char ch) {//遇到右括号使用的方法
		while (!theStack.isEmpty()) {//如果栈不为空
			char chx = theStack.pop();//取栈顶元素
			if (chx == '(')//遇到左括号,不做操作
				break;
			else//否则输出
				output = output + chx;
		}
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -