我正在尝试使用一个循环遍历二维数组中的所有元素。
这是我的代码:
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 + " ";
}
}
}
我已经为上述程序中每行注释了索引范围,但由于逻辑错误,它并没有输出。有什么建议吗?
编辑:循环条件必须保持不变。
57
不是魔数,而是数组中元素的总数。 “i” 用作另一个与此无关的数组的索引。 - user2570380