package com.swift.jztk.biz;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import com.google.gson.Gson;
import com.swift.jztk.bean.Result;
import com.swift.jztk.bean.Root;
import com.swift.jztk.dao.IQuestionDao;
import com.swift.jztk.dao.QuestionDaoImpl;
public class QuestionBizImpl implements IQuestionBiz {
IQuestionDao dao = new QuestionDaoImpl();
@Override
public String getQuestions(String testType) {
List<Result> list = null;
if (testType.equals("rand")) {
HashSet<Integer> set = new HashSet<Integer>();//生成一个哈希集合,用于存放随机数
Random ran = new Random();
for (;;) {//无限循环
int n = ran.nextInt(200) + 1;// 1~200间的随机整数,不加1是0到199
set.add(n);// 随机数放到 整数类型的哈希集合中,保证没有相同的整数
if (set.size() == 100) {
break;
}
}
Iterator<Integer> it = set.iterator();//迭代器,用于获取集合中各条内容
while (it.hasNext()) {
int id = it.next();
Result result = dao.getResultById(id);
list.add(result);//加入对象列表集合
Collections.sort(list, new Comparator<Result>() {// 比较器 匿名内部类
@Override
public int compare(Result o1, Result o2) {
int id1 = o1.getId();
int id2 = o2.getId();
return id1 - id2;// 按照id大小从小到大排序
}
});
}
} else if (testType.equals("order")) {
list = dao.getAll();//MVC架构,数据访问层用接口进行连接,得到数据库中全部数据
}
String json=listToJson(list);
return json;
}
//把得到的List<Result>对象列表集合转换成字符串
public String listToJson(List<Result> list) {
Root root = new Root();
root.setResult(list);
root.setStatusCode("000000");
root.setDesc("请求成功");//json实体类对象赋值
Gson gson = new Gson();
String json = gson.toJson(root);//json实体类对象用Gson解析成字符串
return json;
}
}