Results 1 to 3 of 3
Thread: Need help with PascalTriangle
- 11-03-2010, 01:49 PM #1
Member
- Join Date
- Oct 2010
- Posts
- 20
- Rep Power
- 0
Need help with PascalTriangle
Here is my code
And here is what I am getting when I try to run it.Java Code:public class PascalTriangle { private static int[] ptriangle(StringBuilder outputBuffer, int startRow, int thisRow) { if (thisRow == 0) { // terminal case int[] last = new int[1]; last[0] = 1; return last; } int[] nextNum = new int[thisRow + 1]; int[] numAbove = ptriangle(outputBuffer, startRow, thisRow - 1); // compute padding before the line, (padding width) * (#items this line / 2) int padding = 4 * (startRow -thisRow) / 2; padString(outputBuffer, padding, " "); for (int i = 0; i < thisRow; i++) { if (i == 0) { nextNum[i] = 1; } else if (i == thisRow) { nextNum[i] = 0; } else { nextNum[i] = numAbove[i - 1] + numAbove[i]; } // right pad the number to 2 decimal places String number = String.valueOf(nextNum[i]); padString(outputBuffer, (3 - number.length()), " "); outputBuffer.append(number).append(" "); } // for outputBuffer.append("\n"); return nextNum; } /** * pads a string builder with a specified character a given number of times. * @param b * @param padding * @param character */ public static void padString(StringBuilder b, int padding, String character) { for (int i = 0; i < padding; i++) { b.append(character); } } /** * Convenience wrapper method to initially invoke the recursive method * @param outputBuffer * @param startRow */ public static void ptriangle(StringBuilder outputBuffer, int startRow) { ptriangle(outputBuffer, startRow, startRow); } private static void usage() { System.err.println("Usage: PascalsTriangle <depth>"); System.exit(1); } /** * Generates a pascal's triangle to the specified depth. * @param args */ public static void main(String[] args) { if (args.length != 1) { usage(); } String strLine = args[0]; int lines = 0; try { lines = Integer.parseInt(strLine); } catch (NumberFormatException ex) { System.err.println("invalid number: " + strLine); usage(); } if (lines < 1) { System.err.println("lines must be a number greater than 1."); usage(); } StringBuilder outputBuffer = new StringBuilder(); ptriangle(outputBuffer, lines); System.out.println(outputBuffer.toString()); } }
run:
Usage: PascalsTriangle <depth>
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Can anyone tell me what I did wrong.
- 11-03-2010, 01:53 PM #2
That looks like you're compiling it but not running it. Post what you're actually doing. How are you trying to run it?
- 11-03-2010, 01:55 PM #3
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,379
- Blog Entries
- 7
- Rep Power
- 17


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks