package test3;
public class RPN_Operation {
private char[] expChar = new char[100];// 表达式栈
private int expPointer = 0;// 表达式栈指针
private char[] ariStack = new char[100];// 运算符栈
private int top = 0;// 运算符栈指针
private char[] exitChar = new char[100];// 输出栈
private int exitPointer = 0;// 输出栈指针
private String[][] dataStrings = new String[100][5];// 表格数据 100行5列
private String tempString = new String();// 临时字符串
private String result = new String();// 结果字符串
private int row = 0;// 表格数据行
private String computeValue = new String();// 计算值
private final char[] Arithmetic = { '+', '-', '*', '/', '(', ')', '#' };// 运算符
private final char[] Letter = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z' };// 字母表
private final char[] Digit = { '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0' };// 数字表
public RPN_Operation() {
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 5; j++) {
dataStrings[i][j] = new String();//每一个表格数据都是一个String
dataStrings[i][j] = "";//都赋为空
}
}
}
// 判断字符是否为字母
public boolean isLetter(char word) {
int N = 0;
while (N < Letter.length) {
if (word == Letter[N]) {
return true;
}
N++;
}
return false;
}
// 判断字符是否为数字
public boolean isDigit(char word) {
int N = 0;
while (N < Digit.length) {
if (word == Digit[N]) {
return true;
}
N++;
}
return false;
}
// 判断字符是否为算数运算符
public boolean isArithmetic(char word) {
int N = 0;
while (N < Arithmetic.length) {
if (word == Arithmetic[N]) {
return true;
}
N++;
}
return false;
}
// 输出剩余字符串
public void printExpChar() {
tempString = new String();
for (int i = expPointer; i < expChar.length; i++) {
tempString += expChar[i];
System.out.print(expChar[i]);
result += expChar[i];
}
System.out.print("\t\t");
result += "\t\t";
}
// 输出符号栈
public void printAriStack() {
tempString = new String();
for (int i = 0; i < top; i++) {
tempString += ariStack[i];
System.out.print(ariStack[i]);
result += ariStack[i];
}
System.out.print("\t\t");
result += "\t\t";
}
// 输出逆波兰式
public void printExitChar() {
tempString = new String();
for (int i = 0; i < exitPointer; i++) {
tempString += exitChar[i];
System.out.print(exitChar[i]);
result += exitChar[i];
}
System.out.print("\r\n");
result += "\r\n";
}
// 检查输入的中缀表达式中的字符是否合法
public boolean checkString(String checkString) {
char ch;
for (int i = 0; i < checkString.length(); i++) {
ch = checkString.charAt(i);//把checkString中的第i个字符赋给临时字符ch
//charAt(int index)方法是一个能够用来检索特定索引下的字符的String实例的方法.
if (isLetter(ch)) {
continue;
} else if (isDigit(ch)) {
continue;
} else if (isArithmetic(ch)) {
continue;
} else {
return false;
}
}
return true;
}
// 逆波兰分析
public void RPNAnalysis(String expression) {
expChar = expression.toCharArray();
char ch = expChar[expPointer++];
int temp = 0;
if (checkString(expression)) {
System.out.print("步骤\t当前符号\t输入区\t\t运算符号栈\t\t输出区\r\n");
result += "步骤\t当前符号\t输入区\t\t运算符号栈\t\t输出区\r\n";
while (ch != '#') {
if (isArithmetic(ch)) {
switch (ch) {
case '(':
ariStack[top++] = ch;
System.out.print(row + "\t" + ch + "\t");
result += row + "\t" + ch + "\t";
dataStrings[row][0] = row + "";
dataStrings[row][1] = String.valueOf(ch);
printExpChar();
dataStrings[row][2] = tempString;
printAriStack();
dataStrings[row][3] = tempString;
printExitChar();
dataStrings[row][4] = tempString;
row++;
break;
case ')':
while (ariStack[--top] != '(') {
exitChar[exitPointer++] = ariStack[top];
System.out.print(row + "\t" + ch + "\t");
result += row + "\t" + ch + "\t";
dataStrings[row][0] = row + "";
dataStrings[row][1] = String.valueOf(ch);
printExpChar();
dataStrings[row][2] = tempString;
printAriStack();
dataStrings[row][3] = tempString;
printExitChar();
dataStrings[row][4] = tempString;
row++;
}
System.out.print(row + "\t" + ch + "\t");
dataStrings[row][0] = row + "";
result += row + "\t" + ch + "\t";
dataStrings[row][1] = String.valueOf(ch);
printExpChar();
dataStrings[row][2] = tempString;
printAriStack();
dataStrings[row][3] = tempString;
printExitChar();
dataStrings[row][4] = tempString;
row++;
break;
case '+':
case '-':
temp = top - 1;
if (temp >= 0
&& (ariStack[temp] == '*' || ariStack[temp] == '/')) {
exitChar[exitPointer++] = ariStack[temp];
top--;
} else if (temp >= 0
&& (ariStack[temp] == '-' || ariStack[temp] == '+')
&& (expChar[expPointer + 1] != '*' || expChar[expPointer + 1] != '/')) {
exitChar[exitPointer++] = ariStack[temp];
top--;
}
while (top < 0 && ariStack[temp] != '(') {
exitChar[exitPointer++] = ariStack[temp];
top--;
}
ariStack[top++] = ch;
System.out.print(row + "\t" + ch + "\t");
result += row + "\t" + ch + "\t";
dataStrings[row][0] = row + "";
dataStrings[row][1] = String.valueOf(ch);
printExpChar();
dataStrings[row][2] = tempString;
printAriStack();
dataStrings[row][3] = tempString;
printExitChar();
dataStrings[row][4] = tempString;
row++;
break;
case '*':
case '/':
temp = top - 1;
if (temp >= 0
&& (ariStack[temp] == '*' || ariStack[temp] == '/')) {
exitChar[exitPointer++] = ariStack[temp];
top--;
}
ariStack[top++] = ch;
System.out.print(row + "\t" + ch + "\t");
result += row + "\t" + ch + "\t";
dataStrings[row][0] = row + "";
dataStrings[row][1] = String.valueOf(ch);
printExpChar();
dataStrings[row][2] = tempString;
printAriStack();
dataStrings[row][3] = tempString;
printExitChar();
dataStrings[row][4] = tempString;
row++;
break;
default:
break;
}
} else if (isLetter(ch) || isDigit(ch)) {
exitChar[exitPointer++] = ch;
System.out.print(row + "\t" + ch + "\t");
result += row + "\t" + ch + "\t";
dataStrings[row][0] = row + "";
dataStrings[row][1] = String.valueOf(ch);
printExpChar();
dataStrings[row][2] = tempString;
printAriStack();
dataStrings[row][3] = tempString;
printExitChar();
dataStrings[row][4] = tempString;
row++;
}
ch = expChar[expPointer++];
}
while (top != 0) {
temp = top - 1;
if (ariStack[temp] == '(') {
top--;
continue;
}
exitChar[exitPointer++] = ariStack[--top];
System.out.print(row + "\t" + ch + "\t");
result += row + "\t" + ch + "\t";
dataStrings[row][0] = row + "";
dataStrings[row][1] = String.valueOf(ch);
printExpChar();
dataStrings[row][2] = tempString;
printAriStack();
dataStrings[row][3] = tempString;
printExitChar();
dataStrings[row][4] = tempString;
row++;
}
}
}
// 计算值
public void computeValue() {
int stack[] = new int[100];
exitChar[exitPointer++] = '#';
char ch;
int i = 0, top = 0;
ch = exitChar[i++];
while (ch != '#') {
switch (ch) {
case '+':
computeValue += stack[top - 1] + " + " + stack[top];
stack[top - 1] = stack[top - 1] + stack[top];
computeValue += " := " + stack[top - 1] + "\r\n";
top--;
break;
case '-':
computeValue += stack[top - 1] + " - " + stack[top];
stack[top - 1] = stack[top - 1] - stack[top];
computeValue += " := " + stack[top - 1] + "\r\n";
top--;
break;
case '*':
computeValue += stack[top - 1] + " * " + stack[top];
stack[top - 1] = stack[top - 1] * stack[top];
computeValue += " := " + stack[top - 1] + "\r\n";
top--;
break;
case '/':
computeValue += stack[top - 1] + " / " + stack[top];
stack[top - 1] = stack[top - 1] / stack[top];
computeValue += " := " + stack[top - 1] + "\r\n";
top--;
break;
default:
top++;
stack[top] = ch - '0';
break;
}
ch = exitChar[i++];
}
computeValue += "结果:" + stack[top];
System.out.print(computeValue);
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public String[][] getDataStrings() {
return dataStrings;
}
public void setDataStrings(String[][] dataStrings) {
this.dataStrings = dataStrings;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public char[] getExitChar() {
return exitChar;
}
public void setExitChar(char[] exitChar) {
this.exitChar = exitChar;
}
public String getcomputeValue() {
return computeValue;
}
public void setcomputeValue(String computeValue) {
this.computeValue = computeValue;
}
}
package test3;
import java.io.*;
import org.eclipse.swt.SWT;//这儿必须要添加swt的jar包到路径中来
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
//import com.swtdesigner.SWTResourceManager;
public class RPNSWT {
protected Shell shell;
private Text text;
private Table varTable;
private Text resultText;
private Table resultTable;
private MessageBox messageBox;
private TableEditor editor;
private String result = "";
private File sourceFile = null;
private RPN_Operation mOperation;//定义一个RPN_Operation类的对象
private String analysisString;
String computeValueString = new String();
private int varTableRow = 0;
private char[] varTableVar;
private char[] exitChar;
/**
* Launch the application.
*
* @param args
*/
public static void main(String[] args) {
try {
RPNSWT window = new RPNSWT();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setSize(500, 554);
shell.setText("逆波兰表达式的产生及计算");
Menu menu = new Menu(shell, SWT.BAR);
shell.setMenuBar(menu);
MenuItem menuItem = new MenuItem(menu, SWT.NONE);
menuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
newTextTable();
}
});
menuItem.setText("\u65B0\u5EFA");
MenuItem menuItem_1 = new MenuItem(menu, SWT.NONE);
menuItem_1.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
openFile();
}
});
menuItem_1.setText("\u6253\u5F00");
MenuItem menuItem_2 = new MenuItem(menu, SWT.NONE);
menuItem_2.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
try {
analysis();
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
menuItem_2.setText("\u5206\u6790");
MenuItem menuItem_6 = new MenuItem(menu, SWT.NONE);
menuItem_6.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
try {
computeValue();
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
menuItem_6.setText("\u8BA1\u7B97");
MenuItem menuItem_3 = new MenuItem(menu, SWT.NONE);
menuItem_3.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
saveFile();
}
});
menuItem_3.setText("\u4FDD\u5B58");
MenuItem menuItem_4 = new MenuItem(menu, SWT.NONE);
menuItem_4.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
shell.dispose();
}
});
menuItem_4.setText("\u9000\u51FA");
ScrolledComposite scrolledComposite = new ScrolledComposite(shell,
SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
scrolledComposite.setBounds(10, 10, 202, 119);
scrolledComposite.setExpandHorizontal(true);
scrolledComposite.setExpandVertical(true);
text = new Text(scrolledComposite, SWT.BORDER);
scrolledComposite.setContent(text);
scrolledComposite
.setMinSize(text.computeSize(SWT.DEFAULT, SWT.DEFAULT));
varTable = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION);
varTable.setBounds(218, 10, 127, 119);
varTable.setHeaderVisible(true);
varTable.setLinesVisible(true);
editor = new TableEditor(varTable);
editor.horizontalAlignment = SWT.LEFT;
editor.grabHorizontal = true;
createEditorContents();
TableColumn tableColumn = new TableColumn(varTable, SWT.NONE);
tableColumn.setWidth(61);
tableColumn.setText("\u53D8\u91CF");
TableColumn tblclmnNewColumn = new TableColumn(varTable, SWT.NONE);
tblclmnNewColumn.setWidth(61);
tblclmnNewColumn.setText("\u503C");
ScrolledComposite scrolledComposite_1 = new ScrolledComposite(shell,
SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
scrolledComposite_1.setBounds(351, 10, 123, 119);
scrolledComposite_1.setExpandHorizontal(true);
scrolledComposite_1.setExpandVertical(true);
resultText = new Text(scrolledComposite_1, SWT.BORDER | SWT.H_SCROLL
| SWT.V_SCROLL | SWT.CANCEL);
//resultText.setBackground(SWTResourceManager
// .getColor(SWT.COLOR_LIST_BACKGROUND));
resultText.setEditable(false);
scrolledComposite_1.setContent(resultText);
scrolledComposite_1.setMinSize(resultText.computeSize(SWT.DEFAULT,
SWT.DEFAULT));
resultTable = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION);
resultTable.setBounds(10, 135, 464, 356);
resultTable.setHeaderVisible(true);
resultTable.setLinesVisible(true);
TableColumn tblclmnNewColumn_1 = new TableColumn(resultTable, SWT.NONE);
tblclmnNewColumn_1.setResizable(false);
tblclmnNewColumn_1.setWidth(59);
tblclmnNewColumn_1.setText("\u6B65\u9AA4");
TableColumn tblclmnNewColumn_2 = new TableColumn(resultTable, SWT.NONE);
tblclmnNewColumn_2.setWidth(100);
tblclmnNewColumn_2.setText("\u5F53\u524D\u7B26\u53F7");
TableColumn tblclmnNewColumn_3 = new TableColumn(resultTable, SWT.NONE);
tblclmnNewColumn_3.setWidth(100);
tblclmnNewColumn_3.setText("\u8F93\u5165\u533A");
TableColumn tblclmnNewColumn_4 = new TableColumn(resultTable, SWT.NONE);
tblclmnNewColumn_4.setWidth(100);
tblclmnNewColumn_4.setText("\u8FD0\u7B97\u7B26\u53F7\u6808");
TableColumn tblclmnNewColumn_5 = new TableColumn(resultTable, SWT.NONE);
tblclmnNewColumn_5.setWidth(100);
tblclmnNewColumn_5.setText("\u8F93\u51FA\u533A");
}
public void openFile() {
FileDialog openFileDialog = new FileDialog(shell, SWT.OPEN);
openFileDialog.setText("选择需要分析的文件");
openFileDialog.setFilterExtensions(new String[] { "*.txt" });
openFileDialog.setFilterNames(new String[] { "txt文本文件(*.txt)" });
openFileDialog.setFilterPath("D:\\");
String selectedOpenFile = openFileDialog.open();
this.result = "";
if (selectedOpenFile != null) {
sourceFile = new File(selectedOpenFile);
try {
FileReader fileReader = new FileReader(sourceFile);
BufferedReader reader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String lineString = null;
while ((lineString = reader.readLine()) != null) {
stringBuffer.append(lineString);
stringBuffer.append("\n");
}
text.setText(stringBuffer.toString());
shell.setText("逆波兰表达式分析器 - " + openFileDialog.getFileName());
fileReader.close();
varTable.removeAll();
resultTable.removeAll();
} catch (Exception e) {
e.printStackTrace();
}
} else {
messageBox = new MessageBox(shell, SWT.ICON_WARNING);
messageBox.setMessage("文件未载入!请重新打开需要分析的文件!");
messageBox.setText("提示");
messageBox.open();
}
}
public void newTextTable() {
this.result = "";
this.text.setText("");
this.resultText.setText("");
this.varTable.removeAll();
this.resultTable.removeAll();
}
public void saveFile() {
if (result != "") {
result += "\r\n" + computeValueString;
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter("Result.txt");
fileWriter.write(result);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
Runtime runtime = Runtime.getRuntime();
messageBox = new MessageBox(shell);
messageBox.setMessage("保存成功!");
messageBox.setText("提示");
fileWriter.flush();
fileWriter.close();
messageBox.open();
sourceFile = new File("Result.txt");
runtime.exec("rundll32 url.dll FileProtocolHandler "
+ sourceFile.getAbsolutePath());
} catch (Exception e2) {
e2.printStackTrace();
}
}
} else {
messageBox = new MessageBox(shell, SWT.ICON_WARNING);
messageBox.setMessage("未分析,保存失败!");
messageBox.setText("提示");
messageBox.open();
}
}
public void analysis() {
mOperation = new RPN_Operation();
this.resultTable.removeAll();
this.varTable.removeAll();
this.resultText.setText("");
this.analysisString = text.getText();
this.result = "";
boolean flag = false;
if (mOperation.checkString(this.analysisString)) {
flag = true;
}
if (this.analysisString.equals("")) {
messageBox = new MessageBox(shell, SWT.ICON_WARNING);
messageBox.setMessage("请输入需要分析的字符串或打开需要分析的文件!");
messageBox.setText("提示");
messageBox.open();
} else if (flag) {
if (analysisString.charAt(analysisString.length() - 1) != '#') {
analysisString += "#";
}
this.result = "";
mOperation.RPNAnalysis(this.analysisString);
for (int i = 0; i < mOperation.getRow(); i++) {
TableItem item = new TableItem(resultTable, SWT.NULL);
for (int j = 0; j < 5; j++) {
item.setText(j, mOperation.getDataStrings()[i][j]);
}
}
this.result = mOperation.getResult();
showVariable();
} else {
messageBox = new MessageBox(shell, SWT.ICON_WARNING);
messageBox.setMessage("输入的字符串有错误!");
messageBox.setText("提示");
messageBox.open();
}
}
public void showVariable() {
for (int i = 0; i < analysisString.length(); i++) {
if (mOperation.isLetter(analysisString.charAt(i))
|| mOperation.isDigit(analysisString.charAt(i))) {
varTableRow++;
}
}
varTableVar = new char[varTableRow];
varTableRow = 0;
for (int i = 0; i < analysisString.length(); i++) {
if (mOperation.isLetter(analysisString.charAt(i))
|| mOperation.isDigit(analysisString.charAt(i))) {
varTableVar[varTableRow] = analysisString.charAt(i);
varTableRow++;
}
}
boolean flag = true;
for (int i = 0; i < varTableRow; i++) {
for (int j = 0; j < varTable.getItems().length; j++) {
if (varTableVar[i] == varTable.getItems()[j].getText()
.charAt(0)) {
flag = false;
}
}
if (flag) {
TableItem item = new TableItem(varTable, SWT.NULL);
item.setText(0, String.valueOf(varTableVar[i]));
if (mOperation.isDigit(varTableVar[i])) {
item.setText(1, String.valueOf(varTableVar[i]));
} else {
item.setText(1, "");
}
}
flag = true;
}
}
public void createEditorContents() {
varTable.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent event) {
Control old = editor.getEditor();
if (old != null) {
old.dispose();
}
Point point = new Point(event.x, event.y);
final TableItem item = varTable.getItem(point);
if (item != null) {
int column = -1;
for (int i = 1, n = varTable.getColumnCount(); i < n; i++) {
Rectangle rectangle = item.getBounds(i);
if (rectangle.contains(point)) {
column = i;
break;
}
}
if (column >= 0) {
final Text text = new Text(varTable, SWT.NONE);
text.setText(item.getText(column));
text.selectAll();
text.setFocus();
editor.setEditor(text, item, column);
final int col = column;
text.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent arg0) {
item.setText(col, text.getText());
}
});
}
}
}
});
}
public char setValue(char var) {
for (int i = 0; i < varTable.getItems().length; i++) {
if (var == varTable.getItems()[i].getText().charAt(0)) {
return varTable.getItems()[i].getText(1).charAt(0);
}
}
return var;
}
public void computeValue() {
if (result == "") {
messageBox = new MessageBox(shell, SWT.ICON_WARNING);
messageBox.setMessage("计算失败!请先分析!");
messageBox.setText("提示");
messageBox.open();
} else {
exitChar = new char[mOperation.getExitChar().length];
exitChar = mOperation.getExitChar();
for (int i = 0; i < exitChar.length; i++) {
exitChar[i] = setValue(exitChar[i]);
}
mOperation.setExitChar(exitChar);
mOperation.computeValue();
computeValueString = mOperation.getcomputeValue();
System.out.print(computeValueString);
resultText.setText(computeValueString);
}
}
}
1.使用swt需注意的东西。
SWT(Standard Widget Toolkit) Standard Widget Toolkit是一个开源的GUI编程框架,与AWT/Swing有相似的用处,著名的开源IDE-eclipse就是用SWT开发的。 在SWT之前,Sun已经提供了一个跨平台GUI开发工具包AWT (Abstract Windowing Toolkit).AWT框架底层使用原生窗口部件(native widgets)构建,只能使用各个平台窗口部件的子集。
import org.eclipse.swt.SWT;//这儿导入SWT包时必须要添加swt的jar包到路径中来
方法:
F:\开发工具\JAVA开发\eclipse 这个路径就是我安装eclipse的路径,swt的jar包不用到网上下载,在F:\开发工具\JAVA开发\eclipse\plugins 下就有,直接添加到环境中即可。
2.//import com.swtdesigner.SWTResourceManager;
//resultText.setBackground(SWTResourceManager
// .getColor(SWT.COLOR_LIST_BACKGROUND));