1 import java.applet.*;
2 import java.awt.*;
3 import java.awt.event.*;
4 import java.awt.Graphics.*;
5 /**
6 * Applet to find the nth row of Pascal's Triangle
7 * Creation date: (01/27/2002 9:48:20 PM)
8 * Modified date: (04/15/2002 2:49:00 PM)
9 * @author: Andrew Freed, arf132@psu.edu
10 */
11
12 /*
13 Development of this applet was sponsored by the Penn State Fund for
14 Excellence in Learning and Teaching (FELT), project "Java-based
15 Teaching of Mathematics in Information Sciences and Technology",
16 supervised by Frank Ritter and David Mudgett.
17 */
18
19 public class PascalApplet extends Applet {
20 private Button btnGo = new Button();
21 private ScrollPane pneDisplay = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);
22 private Label lblAnswer = new Label();
23 private Label lblInstruction = new Label();
24 private TextField txtNumRows = new TextField();
25
26 /**
27 * Function that will return a string value containing the nth Pascal row
28 */
29 String getPascalRow(int rowNum)
30 {
31 //Trivial cases
32 if( rowNum < 0 )
33 return "Please input a valid row number";
34 if( rowNum == 0 )
35 return "1";
36 if( rowNum == 1 )
37 return "1 1";
38
39 //Otherwise, we will build up the triangle row by row until we get the row we need
40 int oldRow[] = {1,1};
41 int curRow[] = {};
42 for( int rowIdx = 2; rowIdx <= rowNum; rowIdx++ )
43 {
44 //Create a new row with the proper number of entries, also with "1" at both ends.
45 curRow = new int[rowIdx+1];
46 curRow[0]=1;
47 curRow[rowIdx]=1;
48
49 //The rest of the entries are figured out from the previous row
50 for(int col=1; col < rowIdx; col++)
51 {
52 curRow[col] = oldRow[col-1] + oldRow[col];
53 }
54
55 //Advance to the next row
56 oldRow = curRow;
57 }
58
59 //Print the results to a string
60 //Bracket the middle value(s) for easier interpretation
61 String result = new String();
62 for(int col = 0; col <= rowNum; col++ )
63 {
64 if( col * 2 == rowNum )
65 result += (" [" + intToString(curRow[col]) + "] ");
66
67 else if( 2*col == rowNum -1 || 2*col == rowNum + 1 )
68 result += (" [" + intToString(curRow[col]) + "] ");
69
70 else
71 result += (" " + intToString(curRow[col]) + " ");
72 }
73 return result;
74 }
75
76 //This method takes an integer value and converts it to a string with commas placed
77 //every three digits from the right.
78 private String intToString(int myInt)
79 {
80 String result = "";
81 String buf = new Integer(myInt).toString();
82 boolean isNegative = false;
83 int numCommas = 0;
84
85 if( myInt < 0 )
86 {
87 //Truncate sign
88 isNegative = true;
89 buf = buf.substring(1);
90 }
91
92 int len = buf.length();
93
94 //Short case, no commas
95 if( len <= 3 )
96 {
97 if( isNegative )
98 result = "-" + buf;
99 else
100 result = buf;
101
102 return result;
103 }
104
105 //Otherwise place the first comma from the *left*
106 //At each step, remove from the buffer what has been added to the result
107 int firstComma = len % 3;
108 if( firstComma == 0 )
109 {
110 firstComma += 3;
111 result = buf.substring(0, 3) + ",";
112 buf = buf.substring(3);
113 }
114 else
115 {
116 result = buf.substring(0, firstComma) + ",";
117 buf = buf.substring(firstComma);
118 }
119 numCommas++;
120
121 // Truncation of integer division on purpose -- 4, 5, 6 digit numbers each have the
122 // same number of commas
123 while( numCommas < ((len-1) /3) )
124 {
125 result += buf.substring(0, 3) + ",";
126 buf = buf.substring(3);
127 numCommas++;
128 }
129 result += buf;
130
131 //Re-attach the sign if necessary
132 if( isNegative)
133 result = "-" + result;
134
135 return result;
136 }
137
138 /**
139 * Initializes the applet.
140 */
141 public void init() {
142 try {
143 super.init();
144 setName("PascalApplet");
145 setLayout(null);
146 setSize(500, 300);
147 pneDisplay.setBounds(15, 150, 400, 50);
148 btnGo.setBounds(216, 21, 56, 23);
149 btnGo.setLabel("Go!");
150 lblAnswer.setText("");
151 lblInstruction.setText("Row number:");
152 lblInstruction.setBounds(22, 18, 109, 23);
153 txtNumRows.setBounds(143, 17, 48, 29);
154
155 pneDisplay.add(lblAnswer);
156 add(pneDisplay);
157 add(lblInstruction);
158 add(txtNumRows);
159 add(btnGo);
160
161
162 btnGo.addActionListener(new java.awt.event.ActionListener(){
163 public void actionPerformed(java.awt.event.ActionEvent e)
164 {
165 makeCall();
166
167 //Very odd... I can't get the scrollbars to show up
168 //until I do this!
169 pneDisplay.doLayout();
170 }
171 });
172 txtNumRows.addActionListener(new java.awt.event.ActionListener(){
173 public void actionPerformed(java.awt.event.ActionEvent e)
174 {
175 makeCall();
176
177 //Very odd... I can't get the scrollbars to show up
178 //until I do this!
179 pneDisplay.doLayout();
180 }
181 });
182
183 txtNumRows.requestFocus();
184
185 } catch (java.lang.Throwable Exc) {
186 handleException(Exc);
187 }
188 }
189
190 //Interface function that gathers text input and sends value to code.
191 //Also sets output boxes with output value.
192 private void makeCall()
193 {
194 String strInput = txtNumRows.getText();
195 lblAnswer.setText("");
196
197 if( strInput == null )
198 lblAnswer.setText("Please type in the row number first");
199 else
200 lblAnswer.setText(getPascalRow(Integer.parseInt(strInput)));
201 }
202
203
204 /**
205 * Called whenever the part throws an exception.
206 * @param exception java.lang.Throwable
207 */
208 private void handleException(java.lang.Throwable exception) {
209
210 /* Uncomment the following lines to print uncaught exceptions to stdout */
211 // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
212 // exception.printStackTrace(System.out);
213 }
214
215 //main allows the applet to be run as a standalone application
216 /**
217 * main entrypoint - starts the part when it is run as an application
218 * @param args java.lang.String[]
219 */
220 public static void main(java.lang.String[] args) {
221 try {
222 Frame frame = new java.awt.Frame();
223 PascalApplet aPascalApplet;
224 Class iiCls = Class.forName("PascalApplet");
225 ClassLoader iiClsLoader = iiCls.getClassLoader();
226 aPascalApplet = (PascalApplet)java.beans.Beans.instantiate(iiClsLoader,"PascalApplet");
227 frame.add("Center", aPascalApplet);
228 frame.setSize(aPascalApplet.getSize());
229 frame.addWindowListener(new java.awt.event.WindowAdapter() {
230 public void windowClosing(java.awt.event.WindowEvent e) {
231 System.exit(0);
232 };
233 });
234 frame.show();
235 java.awt.Insets insets = frame.getInsets();
236 frame.setSize(frame.getWidth() + insets.left + insets.right, frame.getHeight() + insets.top + insets.bottom);
237 frame.setVisible(true);
238 } catch (Throwable exception) {
239 System.err.println("Exception occurred in main() of java.applet.Applet");
240 exception.printStackTrace(System.out);
241 }
242 }
243
244 }
245