-2

I wrote a code in Java to generate a Pascal's Triangle. I have two laptops at home, one with Windows Vista Home Basic and the other with Windows 8.1 SingleLanguage, both having the same version of java loaded. The below mentioned code works perfectly fine in Win Vista but gives a logical error when I try to run the same code on Win 8.1. What could be a possible reason for this?

This is the draft of the code that I compiled lately :

import java.util.*;
class PascalsTriangle
{
    int ROW,max=0;
    void main ()
    {
        Scanner sc = new Scanner ( System.in );
        System.out.println(" Input the number of rows in the Pascals Triangle to be generated. ");
        ROW = sc.nextInt();
        int[][] pascal = new int [ROW+1][];
        pascal[1] = new int [1+2];
        pascal[1][1] = 1;
        int i,k=0,j,len=0;
        String str="";
        for( i=2;i<=ROW;i++ )
        {
            pascal[i] = new int [i+2];
            for( j=i;j<pascal[i].length-1;j++ )
            {
                pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j];
                str = Integer.toString(pascal[i][j]);
                len = str.length();
                if( len>max )
                {
                    max = len;
                }
            }
        }
        for( i=1;i<=ROW;i++ )
        {
            for( k=ROW;k>i;k-- )
            {
                System.out.format( "%-" + max + "s", " " );
            }
            for( j=i;j<pascal[i].length-1;j++ )
            {
                System.out.format( "%-" + (max+max) + "s", pascal[i][j] );
            }
            System.out.println();
        }
    }
javac
  • 2,431
  • 4
  • 17
  • 26

1 Answers1

0

void main() seems to work only on some java Versions. I write it as

class PascalsTriangle
{
  public static void main (String[] args)
  {
    int ROW,max=0;
    Scanner sc = new Scanner ( System.in );
    System.out.println(" Input the number of rows in the Pascals Triangle to be generated. ");

// ...

But I get only the first "1" in a descending position, which is quite a good start in every sense. ;-)

EDIT: next things found

Then you start with position i in line 19, at

     for( j=i;j<pascal[i].length-1;j++ )

I definitely would start at position 2, not at position i. Or you should update both values, the left and the right one, using symmetrie for optimisation.

The same at output: how do you get 4 values in row 4 when you only start at position i?

If I start adding at position 2 in line 19, and start output in position 1, everything looks good.

flaschenpost
  • 2,205
  • 1
  • 14
  • 29