import java.applet.*; import java.awt.*; import java.io.*; public class PascalTriangle extends Applet { TextField ROW; TextArea DISPLAY; public static void main(String args[]) { PascalTriangle pt = new PascalTriangle(); Frame appletFrame = new Frame("Pascal Triangle"); appletFrame.add("Center",pt); appletFrame.setSize(500,300); appletFrame.setLocation(50,50); pt.init(); pt.start(); appletFrame.show(); } public void printOut(String s) { int maxDig=0; // number of digits in biggest number in triangle int curDig=0; // number of digits in current element long result=0; // the value of the entry int num = Integer.parseInt(s); DISPLAY.appendText("\n"+s+" Rows of Pascal's Triangle: \n\n"); // This is a crude hack to fix formatting. maxDig=getDigits(calcEntry(num-1,(num-1)/2)); if((maxDig+2)%2 != 1) { // if even number maxDig++; // make odd } // Start for-loops to print out the triangle for(int i=0;ii;k--) { for(int a=maxDig/2;a>=0;a--) { DISPLAY.appendText(" "); // spaces in front of first element } } } DISPLAY.appendText(Long.toString(result)); if(i!=0) { // after first row for(int a=maxDig-curDig;a>=0;a--) { // fewer digits in current entry means more spaces DISPLAY.appendText(" "); // spaces between two elements } } } // end of elements (one row) DISPLAY.appendText("\n"); } // end of all rows } // end printOut method public long calcEntry(int row,int element) { if(element == 0 || element == row) { return 1; } else if(row < 21) { return(doFactorial(row)/(doFactorial(element)*doFactorial(row-element))); } else { return(calcEntry(row-1,element-1)+calcEntry(row-1,element)); } } public long doFactorial(int num) { if(num==0 || num==1) { return 1; } else { return(num*doFactorial(num-1)); } } /** This returns how many digits a (long) number has. */ public int getDigits(long result) { String stringNum=Long.toString(result); return(stringNum.length()); } public boolean action(Event e, Object o) { if(e.target instanceof Button) { printOut(ROW.getText()); return true; } else { return false; } } public void init() { Font font = new Font("fixed",1,10); setLayout(new BorderLayout()); DISPLAY = new TextArea(20,100); add("Center", DISPLAY); if(font.getName() != "fixed") { Font font2 = new Font("Courier",1,10); DISPLAY.setFont(font2); } else { DISPLAY.setFont(font); } Panel SouthPanel = new Panel(); Panel NorthPanel = new Panel(); NorthPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); NorthPanel.add("North",new Label("Rows: ")); ROW = new TextField(10); NorthPanel.add("North",ROW); NorthPanel.add(new Button("Do it")); add("South",SouthPanel); add("North",NorthPanel); } } // end class