- private static void PrintMatrix(){
- //region 使用随机数构建矩阵 (二维数组)
- long seed=System.currentTimeMillis();
- Random objRandom = null;
- int arrLength=4;
- int maxNumber=100;
- int[][] arr=new int[arrLength][arrLength];
- for(int i=0;i<arrLength;i++){
- for(int j=0;j<arrLength;j++){
- int tempNum =0;
- while (tempNum==0){
- objRandom = new Random(seed);
- tempNum = objRandom.nextInt(maxNumber);
- if(tempNum==0){
- seed=System.currentTimeMillis();
- }
- }
- seed=seed+tempNum;
- arr[i][j]=tempNum;
- }
- }
- //endregion
- //region 输出矩阵 (二维数组)
- System.out.print("\r\n");
- System.out.print("\r\n");
- for(int i=0;i<arrLength;i++){
- System.out.print("\t");
- for(int j=0;j<arrLength;j++){
- System.out.print(arr[i][j]);
- System.out.print("\t");
- }
- System.out.print("\r\n");
- }
- System.out.print("\r\n");
- System.out.print("\r\n");
- //endregion
- //region 螺旋输出矩阵内容
- int up,down,left,right;
- up=0;
- down=arrLength-1;
- left=0;
- right=arrLength-1;
- boolean s1=false,s2=false;
- while (true){
- // 从左往右
- if(left<=right){
- for(int i=left;i<=right;i++){
- System.out.print(arr[up][i]+"\t");
- }
- up++;
- }else{
- s1=true;
- up++;
- }
- // 从上往下
- if(up<=down){
- for(int i=up;i<=down;i++){
- System.out.print(arr[i][right]+"\t");
- }
- right--;
- }else{
- s2=true;
- right--;
- }
- // 从右往左
- if(left<=right){
- for(int i=right;i>=left;i--){
- System.out.print(arr[down][i]+"\t");
- }
- down--;
- }else{
- s1=true;
- down--;
- }
- // 从下往上
- if(up<=down){
- for(int i=down;i>=up;i--){
- System.out.print(arr[i][left]+"\t");
- }
- left++;
- }else{
- s2=true;
- left++;
- }
- if(s1==true && s2==true){
- break;
- }
- }
- //endregion
- }
来源: http://www.bubuko.com/infodetail-3413065.html