2D 배열 초기화
각 요소의 유형이 char 인 2D 배열을 초기화하려고합니다 . 지금까지는 다음과 같은 방법으로 만이 배열을 초기화 할 수 있습니다.
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 프로그램 :
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
이것은 유니 코드의 숫자가 \ u0030에서 시작하는 연속이기 때문에 작동합니다 '0'
.
식 '1' + row * 3 + col
(당신이 다양 row
하고 col
사이 0
및 2
포함)는 단순히에서 당신에게 문자를 제공 1
하는 9
.
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);
Shorter way is do it as follows:
private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
Easy to read/type.
table = new char[][] {
"0123456789".toCharArray()
, "abcdefghij".toCharArray()
};
You can use for loop if you really want to.
char table[][] table = new char[row][col];
for(int i = 0; i < row * col ; ++i){
table[i/row][i % col] = char('a' + (i+1));
}
or do what bhesh said.
You can follow what paxdiablo(on Dec '12) suggested for an automated, more versatile approach:
for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
table[row][col] = (char) ('1' + row * 3 + col);
In terms of efficiency, it depends on the scale of your implementation. If it is to simply initialize a 2D array to values 0-9, it would be much easier to just define, declare and initialize within the same statement like this: private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
Or if you're planning to expand the algorithm, the previous code would prove more, efficient.
참고URL : https://stackoverflow.com/questions/13832880/initialize-2d-array
'Programing' 카테고리의 다른 글
부트 스트랩 캐 러셀 스크립트로 정의되지 않은 'offsetWidth'속성을 읽을 수 없음 (0) | 2020.11.19 |
---|---|
Firebase 401 unauthorized error FCM (0) | 2020.11.19 |
Swift-소수점이 0과 같으면 부동 소수점에서 소수점을 제거하는 방법? (0) | 2020.11.19 |
식별자 (id)에 대한 와일드 카드 선택기가 있습니까? (0) | 2020.11.19 |
원격 지점으로 푸시 할 수 없습니다. 지점으로 확인할 수 없습니다. (0) | 2020.11.19 |