Java 输入一个正整数,按蛇形打印。

参考博客:    http://yangyingming.com/article/371/

 1 //输入一个正整数n(n<=30),输出n所对应的蛇形矩阵。举两个例子:
 2 //n=10时,蛇形矩阵为: 
 3 //具体的蛇形矩阵变化路径见下图:
 4 // 
 5 //
 6 //
 7 
 8 import java.util.Scanner;
 9 public class testSheXin {
10 
11     /**
12      * @param args
13      */
14     public static Scanner Sc = new Scanner(System.in);
15     public static void main(String[] args) {
16         // TODO Auto-generated method stub
17         
18         System.out.println("输入一个不大于30的正整数");
19         int num=0;
20         try{
21              num = Sc.nextInt();    
22         }catch(Exception e){
23             e.printStackTrace();
24         }
25         Print(num);
26         
27         
28 
29     }
30     
31     private static int [][] CreatAry(int num ){
32         int temp = num , rowid = 0 , colid = 0 ;
33         int xcot = 1 ;//斜角长度
34         int count =0;//当前斜角已有长度;
35         int bol = 1;// 1 表示当前应该横走,-1表示应该竖着走
36         
37         int [][] ina = new int [10][10];
38         while(temp>0){
39             
40             ina[rowid][colid]=temp; 
41             count++;
42             if(count >= xcot){//该换行了(斜行)
43                 xcot++;
44                 count=0;
45                 if(bol==1){
46                     colid++;
47                     bol=-bol;
48                 }else{
49                     rowid++;
50                     bol=-bol;
51                 }
52             }else{             //不需要换行(斜行)
53                 //上次换行后 bol 已经取反,故bol=-1表示此时向斜下走,bol=1 同理;
54                 if(bol==-1){
55                     rowid++;
56                     colid--;
57                 }else{
58                     rowid--;
59                     colid++;
60                 }
61                 
62             }
63             
64             temp--;
65         
66         }
67         return ina;
68     }
69     public static void Print (int num){
70         int [][] ia= CreatAry(num); 
71         for(int i =0;i <ia.length;i++ ){
72             for(int j =0 ; j<ia.length; j++){
73                 if(ia[i][j]!=0){
74                     System.out.print(ia[i][j]+" ");
75                 }
76             }
77             System.out.println();
78         }
79     }
80 }

猜你喜欢

转载自www.cnblogs.com/Walker-r/p/10574358.html