/* A demo of VT100 control Uses the Screen class. */ import Utilities.*; import java.io.*; public class PascalTriangle { // Data field private int pascalTriangle[][]; private BufferedReader console; // Builds a Pascal triangle. public void buildTriangle(int height) { pascalTriangle = new int[height][]; // Start with the first row. pascalTriangle[0] = new int[1]; pascalTriangle[0][0] = 1; // Build the remaining rows, one row at a time. int row = 1; while (row < pascalTriangle.length) { int lastRow[] = pascalTriangle[row-1]; int newRow[] = new int[row+1]; // Store 1 in the first and last elements of the row. newRow[0] = 1; newRow[newRow.length - 1] = 1; // Fill in the middle of the row. for(int i = 1; i < (newRow.length - 1); i++) newRow[i] = lastRow[i-1] + lastRow[i]; pascalTriangle[row] = newRow; row++; } } // Display Pascal triangle public void showTriangle() { Screen.clearScreen(); Screen.moveCursor(1,1); for (int row=1; row<pascalTriangle.length; row++) { for (int col=0; col<pascalTriangle[row].length; col++) { System.out.print(pascalTriangle[row][col] + " "); } System.out.println(); } } // Obtain a number from the keyboard public int getUserInput() { try { console = new BufferedReader(new InputStreamReader(System.in)); Screen.moveCursor(21,1); Screen.setAttribute(Screen.boldAttribute); System.out.println("-------------------------------------------------"); Screen.setAttribute(Screen.normalAttribute); System.out.println("Enter a height for a Pascal Triangle (1 - 16): "); String tall = console.readLine(); try { return Integer.parseInt(tall); } catch (NumberFormatException ex) { System.out.println("Please enter an integer for triangle height."); return 0; } } catch (IOException ex) { ex.printStackTrace(); } return 0; } // Main input loop public static void main(String args[]) { PascalTriangle mytri = new PascalTriangle(); Screen.clearScreen(); int height = mytri.getUserInput(); // Repeat until user enters a non-positive number while (height>0) { mytri.buildTriangle(height+1); mytri.showTriangle(); height = mytri.getUserInput(); } } }