Java 如何打印二维数组中的行和列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19803445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:19:39 来源:igfitidea点击:
How do you print rows and columns in a 2-d array?
提问by user2840682
I'm trying to get this array to display 4 values arranged in a 2x2 array. With what I'm doing so far, I'm getting an array out of bounds error. How can I do this display properly?
我试图让这个数组显示排列在 2x2 数组中的 4 个值。到目前为止,我得到了一个数组越界错误。我怎样才能正确地做这个显示?
import java.util.Scanner;
import java.util.Random;
public class GridPractice
{
public static void main(String[] args)
{
//declarations
Scanner in = new Scanner(System.in);
Random generator = new Random();
int [][] grid; //un-instantiated grid
int size = 0; //number of rows and columns
//get size of grid - no validation & instantiate
System.out.print("Enter size of grid: ");
size = in.nextInt();
grid = new int[size][size];
//fill grid with random number from 1..99
System.out.println();
for (int row=0; row<size; row++)
{
for (int col=0; col<size; col++)
{
grid[row][col] = generator.nextInt(100); //random numbers 0.99 - not 100
}
}
System.out.printf("%2d\n", grid[size][size]);
采纳答案by Jason
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
System.out.printf("%2d ", grid[row][col]);
}
System.out.println();
}
回答by Jj Tuibeo
Try this:
尝试这个:
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println("");
}
plus remove this line, this is the culprit of the exception:
加上删除这一行,这是异常的罪魁祸首:
System.out.printf("%2d\n", grid[size][size]);