[英]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.