初始化二维数组 [英] Initialize 2D array

查看:36
本文介绍了初始化二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试初始化一个二维数组,其中每个元素的类型都是 char.到目前为止,我只能通过以下方式初始化这个数组.

I am trying to initialize a 2D array, in which the type of each element is char. So far, I can only initialize this array in the follow way.

public class ticTacToe 
{
private char[][] table;

public ticTacToe()
{
    table[0][0] = '1';
    table[0][1] = '2';
    table[0][2] = '3';
    table[1][0] = '4';
    table[1][1] = '5';
    table[1][2] = '6';
    table[2][0] = '7';
    table[2][1] = '8';
    table[2][2] = '9';
}
}

我认为如果数组是 10*10,那是很简单的方法.有没有什么有效的方法可以做到这一点?

推荐答案

这样的事情怎么样:

for (int row = 0; row < 3; row ++)
    for (int col = 0; col < 3; col++)
        table[row][col] = (char) ('1' + row * 3 + col);

以下完整的Java程序:

The following complete Java program:

class Test {
    public static void main(String[] args) {
        char[][] table = new char[3][3];
        for (int row = 0; row < 3; row ++)
            for (int col = 0; col < 3; col++)
                table[row][col] = (char) ('1' + row * 3 + col);

        for (int row = 0; row < 3; row ++)
            for (int col = 0; col < 3; col++)
                System.out.println (table[row][col]);
    }
}

输出:

1
2
3
4
5
6
7
8
9

这是可行的,因为 Unicode 中的数字从 u0030 开始是连续的(这是您从 '0' 得到的).

This works because the digits in Unicode are consecutive starting at u0030 (which is what you get from '0').

表达式 '1' + row * 3 + col(在 0 之间改变 rowcol> 和 2 包含)只是给你一个从 19 的字符.

The expression '1' + row * 3 + col (where you vary row and col between 0 and 2 inclusive) simply gives you a character from 1 to 9.

显然,如果你再进一步,这不会给你字符 10(因为这是 两个 字符),但它适用于 3x3 的情况.您必须在那时更改生成数组内容的方法,例如:

Obviously, this won't give you the character 10 (since that's two characters) if you go further but it works just fine for the 3x3 case. You would have to change the method of generating the array contents at that point such as with something like:

String[][] table = new String[5][5];
for (int row = 0; row < 5; row ++)
    for (int col = 0; col < 5; col++)
        table[row][col] = String.format("%d", row * 5 + col + 1);

这篇关于初始化二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆