[英]java two-dimensional array, how do I remove selected rows
我对Java真的很陌生,并且在我知道的所有可能的短语中都用Google进行了搜索。
因此,我有一个由36行12列组成的表,我一直在尝试编写一种方法,该方法将在行已满时删除该行,然后将所有行向下移动,我想我可以使用一个计数来查看是否所有空格加起来为12,然后删除内容,但似乎是随机删除还是根本不删除,任何人都可以帮助Java新手
int count = 0;
for (int i = 0; i < 36; i++){
for (int j = 0; j < 12; j++){
if (table[i][j] != null){
count++;
}
if (count == 12){
table[i][j] = null;
}
}
}
编辑:嗯我尝试了所有建议的答案,但它们似乎都不起作用,即时通讯正试图这样做并像这样输出
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| 1 . . 3 . . . . 5 . . . | < this line should take its place
| a b c d e f g h i j k l | < this line should delete
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| x y . r f s . . . . . . | < this line should move down one
| 1 2 3 4 5 6 7 8 9 0 . . | < this line should move down one
| A B C D E F G H I J K L | < this line should delete
| . . . . . . . . . . . . |
并在下面输出
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| 1 . . 3 . . . . 5 . . . | < this line just moved down
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| . . . . . . . . . . . . |
| x y . r f s . . . . . . | < this line just moved down one
| 1 2 3 4 5 6 7 8 9 0 . . | < this line just moved down one
| . . . . . . . . . . . . |
我已经将所有工作输出,但是删除完整行不起作用
使用下面的代码删除整个行,您需要在first for循环内初始化count
变量。
for(int i = 0; i < 36; i++)
{
count = 0;
//your procession logic
}
if (count == 12)
{
table[i]= null;// this will delete/nullify row
}
您编码
if (count == 12){
table[i][j] = null; // this will delete/nullify element j of i only.
}
您的count
变量在for循环外被初始化为零,只要它总共计算了12个元素,而不是同一行中的12个元素,就使count == 12
真。 不知道这是否是所需的行为。 如果仅在同一行中有12个元素,则应为true,则应在外部for循环的开头放置count = 0
。
同样,当count == 12
为true时,将(i,j)条目设置为null
而不是整个行。 我认为您的代码应类似于:
int count;
for(int i = 0; i < 36; i++)
{
count = 0;
for(int j = 0; j < 12; j++)
{
if(table[i][j] != null)
{
count++;
}
if(count == 12)
{
table[i] = null;
}
}
}
尝试这个:
int count = 0;
for (int i = 0; i < 36; i++){
for (int j = 0; j < 12; j++){
if (table[i][j] != null){
count++;
}
if (count == 12){
if (i<=35)
{
//Initialize temp to a array like TableType[] temp = new TableType[12];
// move i to i+1 row
table[i+1] = table[i];
table[i] = temp;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.