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

时间:2023-01-13 03:38:28

The following code is what I have so far, and nothing is working at all. I am intend to Declares a 7×10 two dimensional array in the main. Pass that array to a method which fills the array with random integers [1,9]. Pass the filled array to a method which prints the two dimensional array with the sum of the row at the end of each row and the sum of the column at the end of each column. Row and column labels must also be printed. Any help will be greatly appreciated.

以下代码是我目前所拥有的,并没有任何工作。我打算在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 个解决方案

#1


1  

There's a lot of issues with this code as you are probably aware. Most of them stem from incorrectly instantiating and accessing arrays. I fixed it up:

您可能已经意识到这个代码存在很多问题。其中大多数源于错误地实例化和访问数组。我把它修好了:

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();
}

There's a lot of places where you are instantiating an array with 0 length. Which is basically just a useless array at that point because you can't put any values into it. Ex:

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

int[] colSums = new int[0];

#2


1  

If you are using Java8. You can do this elegantly by Stream.

如果您使用的是Java8。你可以通过Stream优雅地完成这项工作。

Here is the code:

这是代码:

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


1  

I think the problem in your code is that you initialized the two dim array in the line int[][] toReturn = new int[0][0];. Here you give the array size and dimension, then in the loop you are trying to populate the array based on the toFill length. Because arrays are fixed in size and do not expand dynamically you can not do this.

我认为你的代码中的问题是你在行int [] [] toReturn = new int [0] [0];中初始化了两个dim数组。在这里给出数组大小和维度,然后在循环中尝试根据toFill长度填充数组。由于数组的大小是固定的,并且不会动态扩展,因此无法执行此操作。

Below is the same style code which gots an arrayindexoutofboundsexception. What I suggest to you is that you give the length and dimensions to the method and then initialize the array with these sizes.

下面是相同的样式代码,用于输出arrayindexoutofboundsexception。我建议你给方法的长度和尺寸,然后用这些尺寸初始化数组。

The code below is also getting an exception because of the same problem you did which is initializing the array to a size then trying to add elements to it.

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

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  

There's a lot of issues with this code as you are probably aware. Most of them stem from incorrectly instantiating and accessing arrays. I fixed it up:

您可能已经意识到这个代码存在很多问题。其中大多数源于错误地实例化和访问数组。我把它修好了:

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();
}

There's a lot of places where you are instantiating an array with 0 length. Which is basically just a useless array at that point because you can't put any values into it. Ex:

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

int[] colSums = new int[0];

#2


1  

If you are using Java8. You can do this elegantly by Stream.

如果您使用的是Java8。你可以通过Stream优雅地完成这项工作。

Here is the code:

这是代码:

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


1  

I think the problem in your code is that you initialized the two dim array in the line int[][] toReturn = new int[0][0];. Here you give the array size and dimension, then in the loop you are trying to populate the array based on the toFill length. Because arrays are fixed in size and do not expand dynamically you can not do this.

我认为你的代码中的问题是你在行int [] [] toReturn = new int [0] [0];中初始化了两个dim数组。在这里给出数组大小和维度,然后在循环中尝试根据toFill长度填充数组。由于数组的大小是固定的,并且不会动态扩展,因此无法执行此操作。

Below is the same style code which gots an arrayindexoutofboundsexception. What I suggest to you is that you give the length and dimensions to the method and then initialize the array with these sizes.

下面是相同的样式代码,用于输出arrayindexoutofboundsexception。我建议你给方法的长度和尺寸,然后用这些尺寸初始化数组。

The code below is also getting an exception because of the same problem you did which is initializing the array to a size then trying to add elements to it.

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

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]);
        }
    }
}