Welcome 微信登录

首页 / 操作系统 / Linux / Java的打印输出练习-画圈打印

最近复习Java,发现很多有意思的面试题,颇为经典,这些题目也是学习Java的比较有利于思考的练习题。关于Java的打印输出,今天就列举题一:把1、2、3  . . . n画圈打印出来,例如下图:

据说这道题是深圳某家公司的面试题,网上有解。对此题我考虑再三发现除了用二维数组来解答外,实在想不出合适的办法,因为你只能把这些数据放在一个二维数据中,才好控制水平方向和垂直方向的增减,现列举一种答案供参考:1package org.j2se;2public class SnakePrint {3public static int length = 6;4public static int value = 1;5public static int[][] snake = new int[length][length];6public static Direction lastDirection = Direction.Right;7public static enum Direction {8Right, Down, Left, Up;9}10 public static void initArray() {11 int hori = 0, ver = 0;12 for int c = 0; c < length * length; c++) {13 snake[hori][ver] = value;14 lastDirection = findDirection(hori, ver);15 switch (lastDirection) {16 case Right:17 ver++;18 break;19 case Down:20 hori++;21 break;22 case Left:23 ver--;24 break;25 case Up:26 hori--;27 break;28 default:29 System.out.println("error");30 }31 value++;32 }33 }34 public static Direction findDirection(int hori, int ver) {35 Direction direction = lastDirection;36 switch (direction) {37 case Right: {38 if ((ver == length - 1) || (snake[hori][ver + 1] != 0))39 direction = Direction.Down;40 break;41 }42 case Down: {43 if ((hori == length - 1) || (snake[hori + 1][ver] != 0))44 direction = Direction.Left;45 break;46 }47 case Left: {48 if ((ver == 0) || (snake[hori][ver - 1] != 0))49 direction = Direction.Up;50 break;51 }52 case Up: {53 if (snake[hori - 1][ver] != 0)54 direction = Direction.Right;55 break;56 }57 }58 return direction;59 }60 public static void main(String[] args) {61 initArray();62 for int i = 0; i < length; i++) {63 for int j = 0; j < length; j++) {64 System.out.print(snake[i][j] + " ");65 }66 System.out.println();67 }68 }69 }