码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-03-17 13:56:51      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:private   ast   bcd   length   public   仪表盘   index   ash   成功   

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

 

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

标签:private   ast   bcd   length   public   仪表盘   index   ash   成功   

原文地址:https://www.cnblogs.com/song-wentao/p/12510172.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!