目標(biāo):
將一個二維數(shù)組按順時針輸出。
(推薦教程:java入門)
代碼實(shí)現(xiàn)如下:
public class 順時針輸出二維矩陣 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[][]arr={ {1,2,2,3}, {4,5,4,6}, {7,8,6,9}, {1,2,3,4} }; int k=0; for(int i = 0; i < arr.length;i++){ for(int j = 0;j < arr[0].length;j++){ k++; System.out.print(arr[i][j]+" "); if(k % 4 == 0){ System.out.println(""); } } } System.out.println(""); System.out.println(arr[0].length);//列數(shù) System.out.println(arr.length);//行數(shù) print(arr); } static void print (int[][]arr){ int leftUpRow = 0;//最左行 int leftUpCol = 0;//最左列 int rightDownRow = arr.length-1;//最右列 int rightDownCol = arr[0].length-1;//最右列 while(leftUpRow <= rightDownRow && leftUpCol <= rightDownCol){ int row = leftUpRow, col = leftUpCol; //矩陣的第一行,此時行不變,列++ while(col <= rightDownCol){ System.out.print(arr[row][col++]+" "); } //矩陣右邊第一列 此時行++,列不變 //將 col,row 恢復(fù) col = rightDownCol; row++; while(row <= rightDownRow){ System.out.print(arr[row++][col]+" "); } //矩陣的最下面一行 此時 行不變 列-- //還需要恢復(fù) col row 的值 row = rightDownRow; col--; while(col >= leftUpCol){ System.out.print(arr[row][col--]+" "); } //矩陣最左邊一列,此時行--,列不變 //繼續(xù)恢復(fù) col row的值 col = leftUpCol; row--; while(row > leftUpRow){ System.out.print(arr[row--][col]+" "); } leftUpRow++; leftUpCol++; rightDownRow--; rightDownCol--; } } }
輸出結(jié)果:
立即學(xué)習(xí)“Java免費(fèi)學(xué)習(xí)筆記(深入)”;
1 2 2 3 4 5 4 6 7 8 6 9 1 2 3 4 1 2 2 3 6 9 4 3 2 1 7 4 5 4 6 8
相關(guān)視頻教程推薦:java視頻
以上就是使用java將一個二維數(shù)組順時針輸出的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
java怎么學(xué)習(xí)?java怎么入門?java在哪學(xué)?java怎么學(xué)才快?不用擔(dān)心,這里為大家提供了java速學(xué)教程(入門到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://www.miracleart.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號