我用 Java 编写了一个代码来生成一个帕斯卡三角形。我家里有两台笔记本电脑,一台装有 Windows Vista Home Basic,另一台装有 Windows 8.1 SingleLanguage,两者都加载了相同版本的 java。下面提到的代码在 Win Vista 中运行良好,但当我尝试在 Win 8.1 上运行相同的代码时出现逻辑错误。这可能是什么原因?
这是我最近编译的代码草稿:
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();
}
}