如何使用数字自动填充二维数组(how to automatically populate a 2d array with numbers)

编程入门 行业动态 更新时间:2024-10-28 10:34:37
如何使用数字自动填充二维数组(how to automatically populate a 2d array with numbers)

嗨我想尝试根据用户输入自动填充二维数组。 用户将输入1个数字,此数字将设置2d数组的大小。 然后我想打印出数组的数字。 例如,如果用户输入数字4。 2d数组将是4行乘4列,并且应包含数字1到16,并打印如下。

1-2-3-4 5-6-7-8 9-10-11-12 13-14-15-16

但我正在努力思考能够做到这一点的正确陈述。 目前我的代码只打印出一个包含*的2d数组。

谁有任何想法如何打印出数字,我真的卡住了。 我的代码如下:

public static void main(String args[]){ Scanner input = new Scanner(System.in); System.out.println("Enter room length"); int num1 = input.nextInt(); int num2 = num1; int length = num1 * num2; System.out.println("room "+num1+"x"+num2+"="+length); int[][] grid = new int[num1][num2]; for(int row=0;row<grid.length;row++){ for(int col=0;col<grid[row].length;col++){ System.out.print("*"); } System.out.println(); } }

Hi i am trying to auto populate a 2d array based on user input. The user will enter 1 number, this number will set the size of the 2d array. i then want to print out the numbers of the array. for example , if the user enters the number 4 . the 2d array will be 4 rows by 4 colums, and should contain the number 1 to 16, and print out as follows.

1-2-3-4 5-6-7-8 9-10-11-12 13-14-15-16

But i am struggling to think of the right statement that will do this. for the moment my code just prints out a 2d array containing *.

Has anyone any ideas how i could print out the numbers , i'm really stuck. my code follows:

public static void main(String args[]){ Scanner input = new Scanner(System.in); System.out.println("Enter room length"); int num1 = input.nextInt(); int num2 = num1; int length = num1 * num2; System.out.println("room "+num1+"x"+num2+"="+length); int[][] grid = new int[num1][num2]; for(int row=0;row<grid.length;row++){ for(int col=0;col<grid[row].length;col++){ System.out.print("*"); } System.out.println(); } }

最满意答案

读n值,

int[][] arr = new int[n][n]; int inc=1; for(int i=0;i<n;i++) for(int j=0;j<n;j++) { arr[i][j]=inc; inc++; }

Read n value,

int[][] arr = new int[n][n]; int inc=1; for(int i=0;i<n;i++) for(int j=0;j<n;j++) { arr[i][j]=inc; inc++; }

更多推荐

本文发布于:2023-08-06 06:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1445255.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   如何使用   数字   automatically   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!