如何用随机整数填充二维数组[1,9]并打印出一个二维数组,每行的行数和每列的总和?

时间:2017-11-06 03:47:30

标签: java arrays

以下代码是我到目前为止所做的,根本没有任何工作。我打算在main中声明一个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);

    }

}

3 个答案:

答案 0 :(得分:1)

我认为您的代码中的问题是您在行int[][] toReturn = new int[0][0];中初始化了两个dim数组。在这里给出数组大小和维度,然后在循环中尝试根据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]);
        }
    }
}

答案 1 :(得分: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 :(得分:1)

如果您使用的是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;
  }
}