【问题标题】:2D Array with variable internal array length JAVA具有可变内部数组长度的二维数组 JAVA
【发布时间】:2017-04-20 17:27:37
【问题描述】:

我目前正在编写一些打印帕斯卡三角形的代码。我需要为每一行使用一个二维数组,但不知道如何让内部数组具有可变长度,因为它也总是会根据它是 int 的行而改变,例如:

public int[][] pascalTriangle(int n) {
    int[][] array = new int[n + 1][]
}

如您所见,我知道如何使外部数组具有我需要的帕斯卡三角形的大小,但我不知道如何获得与其当前所在行相对应的行的可变长度.

另外我将如何打印这个二维数组?

【问题讨论】:

  • array[x] = new int[y];,其中y 是给定行的大小(x 是row)。
  • 鉴于我不知道行数,我是否应该在循环中编写它(每个循环将 x 加一)?
  • 行数为n + 1。不知道你在问什么。
  • 我需要为每一行写下我所说的
  • 哦。是的。你会的。

标签: java arrays


【解决方案1】:

基本上你想要发生的是获取每一行的大小。

for(int i=0; i<array.size;i++){//this loops through the first part of array
    for(int j=0;j<array[i].size;j++){//this loops through the now row
          //do something
     }
 }

你现在应该可以使用这个例子来打印三角形了。

【讨论】:

    【解决方案2】:

    这是我在 StackOverFlow 上的第一个答案。我是一名大一新生,刚刚学习了 Java 作为我学位的一部分。 为了让每一步都清楚,我将不同的代码放在不同的方法中。

    说 n 告诉我们要为三角形打印多少行。

    public static int[][] createPascalTriangle(int n){
        //We first declare a 2D array, we know the number of rows
        int[][] triangle = new int[n][];
        //Then we specify each row with different lengths
        for(int i = 0; i < n; i++){
            triangle[i] = new int[i+1];  //Be careful with i+1 here.
        }
        //Finally we fill each row with numbers
        for(int i = 0; i < n; i++){
            for(int j = 0; j <= i; j++){
                triangle[i][j] = calculateNumber(i, j);
            }
        }
        return triangle;
    }
    //This method is used to calculate the number of the specific location
    //in pascal triangle. For example, if i=0, j=0, we refer to the first row, first number.
    public static int calculateNumber(int i, int j){
        if(j==0){
            return 1;
        }
        int numerator = computeFactorial(i);
        int denominator = (computeFactorial(j)*computeFactorial(i-j));
        int result = numerator/denominator;
        return result;
    }
    
    //This method is used to calculate Factorial of a given integer.
    public static int computeFactorial(int num){
        int result = 1;
        for(int i = 1; i <= num; i++){
            result = result * i;
        }
        return result;
    }
    

    最后,在main方法中,我们先创建一个pascalTriangle,然后用for循环打印出来:

    public static void main(String[] args) {
        int[][] pascalTriangle = createPascalTriangle(6);
        for(int i = 0; i < pascalTriangle.length; i++){
            for(int j = 0; j < pascalTriangle[i].length; j++){
                System.out.print(pascalTriangle[i][j] + " ");
            }
            System.out.println();
        }
    }
    

    这将给出如下输出:

    1 
    1 1 
    1 2 1 
    1 3 3 1 
    1 4 6 4 1 
    1 5 10 10 5 1 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多