帕斯卡三角形正确格式化的Java [英] pascal triangle proper formatting java
问题描述
public class PascalTester
{
public static void main(String [] args)
{
Scanner kb = new Scanner(System.in);
System.out.println(欢迎来到帕斯卡的三角形程序!);
System.out.println(请输入您想要的三角形的大小);
int size = kb.nextInt();
int [] [] myArray = new int [size] [size];
myArray = fillArray(myArray);
// myArray = calculateArray(myArray);
printArray(myArray); //打印数组
}
private static int [] [] fillArray(int [] [] array)
{
array [0 ] [1] = 1; (int i = 1; i< array.length; i ++)
(int j = 1; j< array [i] .length;数组[i] [j] =数组[i-1] [j-1] +数组[i-1] [j]
}
}
返回数组;
private static void printArray(int [] [] array)
(int i = 0; i< array.length; i ++) (array [i] [j]!= 0)
{
(int j = 0; j {
System.out.print(array [i] [j] +);
}
System.out.println();
code
$ b <现在我唯一的问题是正确地格式化输出看起来像一个实际的三角形。在这个时候,任何建议都会非常有帮助。在此先感谢
解决方案对此的一种方法是,假设您将所有数字格式化为相同的宽度,问题,如集中线的问题。
Java编码留给读者的是练习,但实际上:
for lineText:triange行
leadingSpacesCount =(80/2) - lineText.length();
printx leadingSpacesCount + lineText
so I'm currently working on an assignment that I just can't seem to finish. Well I have everything finished but would like the extra credit. I've been looking around the web and can't really seem to find exactly what I'm looking for.
public class PascalTester
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Welcome to the Pascal's Triangle program!");
System.out.println("Please enter the size of the triangle you want");
int size = kb.nextInt();
int[][] myArray = new int[size][size];
myArray = fillArray(myArray);
//myArray = calculateArray(myArray);
printArray(myArray); //prints the array
}
private static int[][] fillArray(int[][] array)
{
array[0][1] = 1;
for (int i = 1; i < array.length; i++)
{
for (int j = 1; j < array[i].length; j++)
{
array[i][j] = array[i-1][j-1] + array[i-1][j];
}
}
return array;
}
private static void printArray(int[][] array)
{
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if(array[i][j] != 0)
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
The only issue that I'm having now is to properly format the output to look like an actual triangle. Any suggestions would be very helpful at this point in time. Thanks in advance
解决方案 One approach to this, is, assuming you have all numbers formatted to the same width, is to treat the problem as that of centering the lines.
Java Coding left as exercise to reader but essentially:
for lineText : triange lines
leadingSpacesCount = (80/2) - lineText.length();
print " " x leadingSpacesCount + lineText
这篇关于帕斯卡三角形正确格式化的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!