【问题标题】:How do I fill a 2D array with random integers [1,9] and print out a 2D array with sums of rows at each row and sum of columns at each column?如何用随机整数 [1,9] 填充二维数组并打印出一个二维数组,其中每行的行总和以及每列的列总和?
【发布时间】:2017-11-06 03:47:29
【问题描述】:

以下代码是我到目前为止所拥有的,根本没有任何效果。我打算主要声明一个 7×10 的二维数组。将该数组传递给使用随机整数 [1,9] 填充数组的方法。将填充的数组传递给一个方法,该方法打印二维数组,其中每行末尾的行总和以及每列末尾的列总和。还必须打印行和列标签。任何帮助将不胜感激。

package twodimensionalarray;

import java.util.Arrays;
import java.util.Random;

/**
 *
 * @author Kristy7
 */
public class TwoDimensionalArray {

    //This method is for generating random integers between 1 and 9.
    public static int randInt(){
        Random rand = new Random();
        int randNum;
        randNum = rand.nextInt(9)+1;
        return randNum;

    }

    //This method is for filling a 2D array with random integers 
    public static int[][] fillArray(int[][] toFill){
        int[][] toReturn = new int[0][0];

        for(int r = 0; r < toFill.length; r++){
            for(int c = 0; c < toFill[0].length; c++){
                toReturn[toFill[r]][toFill[c]] = randInt(toFill);
            }

        }

        return toReturn;
    }

    //This method is for for summing rows and columns, and printing rows, columns, the sum of ruws at each row, and the sum of columns at each column.
    public static void summingRC(int[][] toSum){
        int[] colSums = new int[0];
        for(int i = 0; i < toSum.length; i++){
            System.out.print(i);
        }
        System.out.println();
        int sum = 0;
    for (int r = 0; r < toSum.length; r++) {

        for (int c = 0; c < toSum[r].length; c++) {
            sum += toSum[c][r];
            colSums[c] += toSum[r][c];
        }

        System.out.println(sum);
    }
    System.out.println(colSums);


    }

    /**
     * @param args the command line arguments
     * 
     */

    public static void main(String[] args) {

        //Declare a 7x10 2D array 
        int [][] twoDArray = new int[7][10];

        //call fillArray method.
        int[][] fillingArray = fillArray(twoDArray);

        //call SummingRC method
        summingRC(fillingArray);

    }

}

【问题讨论】:

  • 提交代码时,请将其粘贴,用鼠标选中,然后在编辑器中按下{}按钮。这将正确格式化它。

标签: java arrays


【解决方案1】:

您可能知道,这段代码存在很多问题。它们中的大多数源于错误地实例化和访问数组。我修好了:

public static int randInt(){
    Random rand = new Random();
    int randNum;
    randNum = rand.nextInt(9)+1;
    return randNum;

}

//This method is for filling a 2D array with random integers 
public static int[][] fillArray(int[][] toFill){
    int[][] toReturn = new int[toFill.length][toFill[0].length];

    for(int r = 0; r < toFill.length; r++){
        for(int c = 0; c < toFill[0].length; c++){
            toReturn[r][c] = randInt();
        }
    }
    return toReturn;
}

//This method is for for summing rows and columns, and printing rows, columns, the sum of ruws at each row, and the sum of columns at each column.
public static void summingRC(int[][] toSum){
    int[] colSum = new int[toSum[0].length];
    int[] rowSum = new int[toSum.length];
    for(int i = 0; i < toSum.length; i++){
        for(int j = 0; j < toSum[i].length; j++){
            colSum[j] += toSum[i][j];
            rowSum[i] += toSum[i][j];
        }
    }
    System.out.println("Matrix: ");
    print2dArray(toSum);
    System.out.println("Col sum:");
    printArray(colSum);
    System.out.println("Row sum:");
    printArray(rowSum);

}

/**
 * @param args the command line arguments
 * 
 */

public static void main(String[] args) {

    //Declare a 7x10 2D array 
    int [][] twoDArray = new int[7][10];

    //call fillArray method.
    int[][] fillingArray = fillArray(twoDArray);

    //call SummingRC method
    summingRC(fillingArray);

}

public static void print2dArray(int[][] arr){
    for(int i = 0; i < arr.length; i++){
        for(int j = 0; j < arr[i].length; j++){
            System.out.print(arr[i][j] +  " ");
        }
        System.out.println();
    }
}

public static void printArray(int arr[]){
    for(int i = 0; i < arr.length; i++){
        System.out.print(arr[i] +  " ");
    }
    System.out.println();
}

在很多地方实例化一个长度为 0 的数组。这在那时基本上只是一个无用的数组,因为您不能将任何值放入其中。例如:

int[] colSums = new int[0];

【讨论】:

    【解决方案2】:

    如果您使用的是 Java8。你可以通过Stream优雅地做到这一点。

    代码如下:

    import java.util.Arrays;
    import java.util.stream.IntStream;
    
    public class Q47129466 {
      public static void main(String[] args) {
        int[][] mat = get(5, 5);
        System.out.println(Arrays.deepToString(mat));
        System.out.println(Arrays.toString(rowSum(mat)));
        System.out.println(Arrays.toString(columnSum(mat)));
      }
    
      public static int[][] get(int width, int height) {
        return IntStream.range(0, height)
            .mapToObj(c -> IntStream.range(0, width)
                .map(r -> (int) (9 * Math.random() + 1))
                .toArray())
            .toArray(int[][]::new);
      }
    
      public static int[] rowSum(int[][] matrix) {
        return Arrays.stream(matrix).mapToInt(row -> IntStream.of(row).sum()).toArray();
      }
    
      public static int[] columnSum(int[][] matrix) {
        return Arrays.stream(matrix).reduce((a, b) -> add(a, b)).orElse(new int[0]);
      }
    
      public static int[] add(int[] a, int[] b) {
        int[] sum = new int[Math.max(a.length, b.length)];
        for (int i = 0; i < sum.length; i++) {
          sum[i] = (i < a.length ? a[i] : 0) + (i < b.length ? b[i] : 0);
        }
        return sum;
      }
    }
    

    【讨论】:

      【解决方案3】:

      我认为您的代码中的问题是您在int[][] toReturn = new int[0][0]; 行中初始化了两个暗淡数组。在这里您给出数组大小和维度,然后在循环中您尝试根据toFill 长度填充数组。因为数组的大小是固定的,并且不会动态扩展,所以您不能这样做。

      下面是相同的样式代码,它得到了一个 arrayindexoutofboundsexception。我建议你给方法提供长度和尺寸,然后用这些尺寸初始化数组。

      下面的代码也出现了异常,因为您遇到了同样的问题,即将数组初始化为一个大小,然后尝试向其中添加元素。

      public static void main(String[] args) {
          int [] []  x =new int[0][0];
      
          for (int i = 0; i < 5; i++) {
              for (int j = 0; j < 5; j++) {
                  x[i][j]=i+j;
      
              }
      
          }
      
      
          for (int i = 0; i < 5; i++) {
              for (int j = 0; j < 5; j++) {
                  System.out.println(x[i][j]);
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-08-13
        • 1970-01-01
        • 2021-12-04
        • 1970-01-01
        • 2021-12-23
        • 1970-01-01
        • 2018-08-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多