当前位置:首页 > 开发 > 编程语言 > Java > 正文

java-顺时针打印图形

发表于: 2012-03-20   作者:bylijinnan   来源:转载   浏览:
摘要: 一个画图程序 要求打印出: 1.int i=5; 2.1 2 3 4 5 3.16 17 18 19 6 4.15 24 25 20 7 5.14 23 22 21 8 6.13 12 11 10 9 7. 8.int i=6 9.1 2 3 4 5 6 10.20 21 22 23 24 7 11.19
一个画图程序 要求打印出:
1.int i=5;   
2.1  2  3  4  5  
3.16 17 18 19 6  
4.15 24 25 20 7  
5.14 23 22 21 8  
6.13 12 11 10 9  
7.  
8.int i=6  
9.1  2  3  4  5   6  
10.20 21 22 23 24  7  
11.19 32 33 34 25  8  
12.18 31 36 35 26  9  
13.17 30 29 28 27 10  
14.16 15 14 13 12 11 

http://bylijinnan.iteye.com/admin/blogs/1401698是类似的
代码如下:
public class SnakePrinter {
	
	private boolean error;
	private Direction direction=Direction.RIGHT;
	private int[][] matrix;
	
	public static void main(String[] args) {
		int n=7;
		SnakePrinter snake=new SnakePrinter();
		snake.initial(n);
		if(!snake.error){
			snake.print();
			//System.out.println(Arrays.deepToString(snake.matrix));
		}
	}

	public void initial(int n){
		if(n<0)return;
		matrix=new int[n][n];
		int row=0,col=0;
		int value=1;
		int max=n*n;
		while(value<=max){
			matrix[row][col]=value;
			direction=findDirection(row,col,n);
			switch(direction){
			case RIGHT:
				col++;
				break;
			case LEFT:
				col--;
				break;
			case DOWN:
				row++;
				break;
			case UP:
				row--;
				break;
			default:
				this.error=true; 
				break;
			}
			value++;
		}
	}
	
	public Direction findDirection(int row,int col,int len){
		if(row<0||col<0||row>=len||col>=len){
			this.error=true;
		}
		Direction direction=this.direction;
		switch(direction){
		case RIGHT:
			if(col==len-1 || matrix[row][col+1]!=0){
				direction=Direction.DOWN;
			}
			break;
		case LEFT:
			if(col==0 || matrix[row][col-1]!=0){
				direction=Direction.UP;
			}
			break;
		case DOWN:
			if(row==len-1 || matrix[row+1][col]!=0){
				direction=Direction.LEFT;
			}
			break;
		case UP:
			if(row==0|| matrix[row-1][col]!=0){
				direction=Direction.RIGHT;
			}
			break;
		default:
			this.error=true; 
			break;
		}
		return direction;
	}
	public void print(){
		if(matrix==null){
			return;
		}
		int len=matrix.length;
		for(int row=0;row<len;row++){
			for(int col=0;col<len;col++){
				System.out.print(matrix[row][col]+" ");
			}
			System.out.println();
		}
	}
	public enum Direction{
		RIGHT,DOWN,LEFT,UP
	}
}

java-顺时针打印图形

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号