简明现代魔法 -> Java编程语言 -> SWT之路:递归计算阶乘
SWT之路:递归计算阶乘
2009-11-30
递归是一个强大的算法,一个简单的例子就是使用递归来计算某数的阶乘。
本程序实现,输入任意一个整数,返回它的阶乘。
package SWT; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class factorial { protected Shell shell; private Text text; static Label resultShow; /** * Launch the application. * @param args */ public static void main(String[] args) { try { factorial window = new factorial(); 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(450, 300); shell.setText("阶乘计算"); { Group group = new Group(shell, SWT.NONE); group.setText("输入需要计算阶乘的数"); group.setBounds(10, 10, 422, 120); { text = new Text(group, SWT.BORDER); text.setBounds(170, 39, 70, 18); } { Button button = new Button(group, SWT.NONE); button.setBounds(170, 77, 72, 22); button.setText("计算"); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { // 读取输入 int input = Integer.parseInt(text.getText()); int result = fac(input); resultShow.setText(input + "的阶乘为" + result); } }); } } { Group group = new Group(shell, SWT.NONE); group.setText("结果"); group.setBounds(10, 141, 422, 115); { resultShow = new Label(group, SWT.NONE); resultShow.setAlignment(SWT.CENTER); resultShow.setBounds(50, 39, 328, 66); //label.setText("New Label"); } } } public int fac(int num){ if(num == 1){ return 1; } return num * fac(num-1); } }