[英]Get 2D array indices from 1D
所以,我試圖使用一個循環遍歷2D數組中的所有元素。
我就在這里:
public class Test {
private static final String[][] key = {
{"`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "Backspace"}, // 0 - 13
{"Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\\"}, // 0 - 13
{"Caps", "A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'", "Enter"}, // 0 - 12
{"Shift", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "/", "\u2191"}, // 0 - 11
{" ", "<", "\u2193", ">"} // 0 - 3
};
public static void main(String[] args) {
final int totalLen = 57;
String str = "";
for (int i = 0, row = 0, col = 0; i < totalLen; ++i, ++col) {
if (row < key.length && i % key[row].length >= key[row].length - 1) {
++row;
col = 0;
System.out.println(str);
str = "";
}
if (row < key.length)
str += col + " ";
}
}
}
我已經評論了上面程序應該輸出的每一行的索引范圍,但它沒有因為邏輯錯誤。 有什么建議?
編輯:循環條件必須保持不變。
您應該能夠使用兩個變量row
和col
來執行此操作,其中col
在循環標頭中遞增,並且row
循環體中有條件地遞增:
for (int row =0, col = 0 ; row != key.length ; col++) {
System.out.println(row + " " + col);
if (col == key[row].length-1) {
row++;
col = 0;
}
}
循環條件不能不同。 對不起,我忘記提及了。
您可以添加i
並在達到totalLen
時停止:
for (int row =0, col = 0, i = 0 ; i != totalLen ; col++, i++) {
System.out.println(row + " " + col);
if (col == key[row].length-1) {
row++;
col = 0;
}
}
但是,這更加脆弱,因為您正確計算了totalLen
的依賴性。
嘗試這個解決方案,它使用單個while
循環和問題中的相同循環條件(根據要求):
String str = "";
int row = 0, col = 0;
int i = 0, totalLen = 57;
while (i < totalLen) {
if (col < key[row].length) {
str += col++ + " ";
i++;
} else {
System.out.println(str);
str = "";
row++;
col = 0;
}
}
System.out.println(str); // prints the last line
或者,如果您更喜歡使用for
循環:
String str = "";
int totalLen = 57;
for (int i = 0, row = 0, col = 0; i < totalLen; i++) {
str += col++ + " ";
if (col == key[row].length) {
row++;
col = 0;
System.out.println(str);
str = "";
}
}
代碼段將在控制台上生成以下輸出:
0 1 2 3 4 5 6 7 8 9 10 11 12 13
0 1 2 3 4 5 6 7 8 9 10 11 12 13
0 1 2 3 4 5 6 7 8 9 10 11 12
0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 3
好吧,我試圖保持你的循環條件......但我沒有使用每個參數。 無論如何,它應該工作:
for (int i = 0, row = 0, col = 0; i < totalLen; ++i, ++col) {
System.out.println("row " + row + ", col " + col);
// what ever you want to do with your loop, do it here
// before altering the row and col parameters
if (col == key[row].length-1) {
col = -1; // if end of the row, set col to -1, it will be incremented in the next loop
row++;
if(row==key.length){
break;
}
}
}
基本上它與@dasblinkenlight幾乎相同 - 只有當row
變量達到key
數組的長度時才引入break
條件。 您還可以測試if(i==totalLen)
但我個人覺得檢查數組長度更可靠。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.