インデックスで位置を指定して、2D配列の要素を印刷しようとしています。たとえば、配列の文字列[1] [0]である場所3を印刷したいとします。
String [] [] fruit = new String [2] [2];
fruit [0] [0] = "apple"; //position 1
fruit [0] [1] = "banana"; //position 2
fruit [1] [0] = "pear"; //position 3
fruit [1] [1] = "melon"; //position 4
「フルーツ[1] [0]」の位置3を呼び出したいので、「位置3」の印刷を要求すると、「梨」が表示されます。
配列はインデックス値0から始まるため、探しているのは明らかにセルの文字どおりの位置です。2D配列では、特定の行の列数が異なる可能性があることにも注意してください。たとえば、1行目と2行目は4列、5行目は6列、6行目、7行目は4列です。配列内のすべての列が実際に特定の長さに固定されていること(「正方形」の2D配列)を確実に知らない限り、このスキームの利点はわかりません。
それでもなお、これは2つのforループ(一方が他方の中にネストされている)を使用して簡単に行うことができます。次に例を示します。
String[][] array = {
{"cell 1", "cell 2"}, // Row 1 (index 0)
{"cell 3", "cell 4", "cell 5"}, // Row 2 (index 1)
{"cell 6", "cell 7"}}; // Row 3 (index 2)
int yourDesiredCell = 5;
int cellCount = 0;
boolean found = false;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
cellCount++;
if (cellCount == yourDesiredCell) {
System.out.println(array[i][j]);
found = true;
break;
//return array[i][j];
}
}
if (found) {
break;
}
}
これをクラスメソッドに配置することもできます。次に例を示します。
public static String getCellData(String[][] array, int yourDesiredCell) {
int cellCount = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
cellCount++;
if (cellCount == yourDesiredCell) {
return array[i][j];
}
}
}
return null;
}
もう1つの便利な方法は、2D配列に含まれる実際のセルの総数を取得することです(まだわからない場合)。
public static int getTotalCellCount(String[][] array) {
int cellCount = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
cellCount++;
}
}
return cellCount;
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加