A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

这是一个工具类,我起的名字叫MemoryBox功能是,记忆输入的数并判断是否数据重复,还可以添加数据的约数条件,用于进行输入判断。
[Java] 纯文本查看 复制代码
import java.util.ArrayList;

public class MemoryBox {
	private MemoryBox(){}
	private static ArrayList<Integer> list = new ArrayList<>();
	private static boolean judgeADJ = false;
	private static int n1,n2;
	public static boolean setNum(int num){
		for (int i = 0; i < list.size(); i++) {
			if(num == list.get(i)){
				return false;
			}
		}
		list.add(num);
		if(judgeADJ){
			if(isAdjacented()){
				return false;
			}
		}
		return true;
	}
	public static boolean setNum(int num,boolean condition){
		//给定条件为false则返回false
		if (!condition) return false;
		for (int i = 0; i < list.size(); i++) {
			if(num == list.get(i)){
				return false;
			}
		}
		list.add(num);
		if(judgeADJ){
			if(isAdjacented()){
				return false;
			}
		}
		return true;
	}
	public static void clearMemory(){
		list.clear();
	}
	public static void addNonadjacentedJudge(int num1,int num2){
		n1 = num1;
		n2 = num2;
		judgeADJ = true;
	}
	public static void removeNonadjacentedJudge(){
		judgeADJ = false;
	}
	//判断集合中两个数是否相邻
	private static boolean isAdjacented(){
		int index1 = findIndexOfNum(n1);
		int index2 = findIndexOfNum(n2);
		if (index1>=0&&index2>=0) {
			if(Math.abs(index1-index2)==1){
				return true;
			}
		}
		return false;
	}
	//找出两个数在集合中的位置
	private static int findIndexOfNum(int num){
		for (int i = 0; i < list.size(); i++) {
			if(num == list.get(i)){
				return i;
			}
		}
		//没找到
		return -1;
	}
}

(请放入eclipse中食用)
下面是类的演示事例,事例解决了1,2,3,4数字不重复的排序问题,并且添加了首位不为4还有3,4不相邻的约束条件。并打印输出:
[Java] 纯文本查看 复制代码
public class Q1234ForObj {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//添加两个数不相邻的约束条件
		MemoryBox.addNonadjacentedJudge(4, 3);
//		MemoryBox.removeNonadjacentedJudge();//约束条件置空
		for (int i = 1; i <= 4; i++) {
			for (int j = 1; j <= 4; j++) {
				for (int k = 1; k <= 4; k++) {
					for (int l = 1; l <= 4; l++) {
							//setNum数据加入记忆盒子,如果加入的数与盒子中的数重复则返回false
							if (MemoryBox.setNum(i)&&MemoryBox.setNum(j)&&MemoryBox.setNum(k)&&MemoryBox.setNum(l)) {
								int num = i*1000+j*100+k*10+l;
								System.out.println(num);
							}
							//清空记忆,准备下次循环
							MemoryBox.clearMemory();
					}
				}
			}
		}
	}

}


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马