输出指定数字随意组合 算法二 (面向对象的思路)

public class Tests2020031702 {
	private static String RANGE = "0123456789";

	public static void main(String[] args) {
		// 1-8位随机组合
		for (int len = 1; len <= 5; len++) {
			DashBoard dashBoard = new DashBoard(len);
			// 初始值
			dashBoard.println();
			while (dashBoard.add()) {
				dashBoard.println();
			}
			// 最大值
			dashBoard.println();
		}
	}

	/**
	 * 仪表盘
	 */
	static class DashBoard {
		char[] chars;
		char lastChar = RANGE.charAt(RANGE.length() - 1);

		public DashBoard(int length) {
			// 仪表盘显示位数
			this.chars = new char[length];
			// 初始化
			for (int i = 0; i< chars.length; i++) {
				chars[i] = RANGE.charAt(0);
			}
		}

		/**
		 * 加1
		 * @return	是否成功
		 */
		public boolean add() {
			// 从最后一位开始累加
			for (int i = chars.length - 1; i >= 0; i--) {
				// 加1
				if(RANGE.indexOf(String.valueOf(chars[i])) < (RANGE.length() - 1)) {
					chars[i] = RANGE.charAt(RANGE.indexOf(String.valueOf(chars[i])) + 1);
					// 不溢出则跳出循环
					break;
				}
				chars[i] = RANGE.charAt(0);
			}
			// 判断是否最大值
			for (int i = 0; i< chars.length; i++) {
				if(chars[i] != lastChar) {
					return true;
				}
			}
			return false;
		}

		/**
		 * 打印
		 */
		public void println() {
			for (int i = 0; i< chars.length; i++) {
				System.out.print(chars[i]);
			}
			System.out.println();
		}
	}
}

 打印

0
1
2
3
4
5
6
7
8
9
00
01
02
03
04

 修改取值范围

private static String RANGE = "abcdefg";

 再打印

a
b
c
d
e
f
g
aa
ab
ac
ad
ae

 

posted on 2020-03-17 13:39  小小程序员的梦想  阅读(315)  评论(0编辑  收藏  举报

导航