Опубликован: 27.09.2006 | Уровень: для всех | Доступ: свободно | ВУЗ: Московский государственный индустриальный университет
Лекция 12:
Проект "Компилятор формул"
Тексты эталонных проектов
Сначала приведем все исходные тексты рекурсивного компилятора формул.
Makefile для рекурсивного компилятора формул
# -*- mode: makefile -*-
.PHONY : run clean
# Запустить тест рекурсивного компилятора формул.
run: RecursCompfTest.class
java RecursCompfTest
# Откомпилировать текст рекурсивного компилятора формул.
RecursCompfTest.class: RecursCompfTest.java RecursCompf.java \
Xterm.java
javac RecursCompfTest.java
# Удалить лишние файлы.
clean:
rm -f *.class *.expandРекурсивный компилятор формул
// Рекурсивный компилятор формул.
public class RecursCompf {
private static final int DEFSIZE = 255;
private char[] str;
private int index;
private void compileF() {
compileT();
if (index >= str.length) return;
if (str[index] == '+'){
index++;
compileF();
Xterm.print("+ ");
return;
}
if (str[index] == '-'){
index++;
compileF();
Xterm.print("- ");
}
}
private void compileT() {
compileM();
if (index >= str.length) return;
if (str[index] == '*'){
index++;
compileT();
Xterm.print("* ");
return;
}
if (str[index] == '/'){
index++;
compileT();
Xterm.print("/ ");
}
}
private void compileM() {
if (str[index] == '(') {
index++;
compileF();
index++;
} else
compileV();
}
private void compileV() {
Xterm.print("" + str[index++] + " ");
}
public void RecursCompf() {
str = new char[DEFSIZE];
}
public void compile(char[] str) {
this.str = str;
index = 0;
compileF();
Xterm.print("\n");
}
}Тест для рекурсивного компилятора формул
// Тест для рекурсивного компилятора формул.
public class RecursCompfTest {
public static void main(String[] args) throws Exception {
RecursCompf c = new RecursCompf();
while (true)
c.compile(Xterm.inputChars("Введите формулу -> "));
}
}