唱票:因为统计票数时需要读出声音来,所以就形象地称为唱票。
代码实现uuid的唯一:
package cn.hncu.booksStore.common.dao.impl;
import java.util.ArrayList;
import java.util.List;
import cn.hncu.booksStore.common.constance.AutoNumEnum;
import cn.hncu.booksStore.common.dao.dao.AutoDao;
import cn.hncu.booksStore.common.vo.AutoNumModel;
import cn.hncu.booksStore.util.FileIOUtil;
public class AutoDaoImpl implements AutoDao {
private final String FILE_NAME = "AutoNum.txt";
@Override
public String getModelNum(AutoNumEnum ane) {
String key = ane.getKey();
String autoNum = ane.getNum();
int hash = key.hashCode();
hash = hash > 0 ? hash : -hash;
hash %= 1000;
// 读取数据
List<AutoNumModel> list = FileIOUtil.readFromFile(FILE_NAME);
if (list == null) {
list = new ArrayList<AutoNumModel>();
}
for (AutoNumModel a : list) {
if (a.getKey().equals(key)) {
final int val = a.getValue();
String num = "" + val;
for (int i = num.length(); i < 3; i++) {
num = 0 + num;
}
num = hash + "-" + autoNum + "-" + num;
a.setValue(val + 1);
FileIOUtil.write2File(FILE_NAME, list);
return num;
}
}
// 如果没有数据
AutoNumModel an = new AutoNumModel();
String num = hash + "-" + autoNum + "-001";
an.setKey(key);
an.setValue(2);
list.add(an);
FileIOUtil.write2File(FILE_NAME, list);
return num;
}
public static void main(String[] args) {
AutoDaoImpl au = new AutoDaoImpl();
String num = au.getModelNum(AutoNumEnum.BOOK);
System.out.println(num);
}
}
这个东西本人写的复杂了,希望对大家有帮助。
辅助枚举:
package cn.hncu.booksStore.common.constance;
public enum AutoNumEnum {
USER("USERNUM", "6666"), BOOK("BOOKNUM", "512"), INMAIN("INMAINNUM", "8888"), INDETAIL(
"INDETAILNUM", "119"), OUTMAIN("OUTMAINNUM", "168"), OUTDETAIL(
"OUTDETAILNUM", "110"), STOCK("STOCKNUM", "222");
private final String key;
private final String num;
private AutoNumEnum(String key, String num) {
this.key = key;
this.num = num;
}
public String getKey() {
return key;
}
public String getNum() {
return num;
}
public static String getKeyByNum(String num) {
for (AutoNumEnum auto : AutoNumEnum.values()) {
if (auto.getNum().equalsIgnoreCase(num)) {
return auto.getKey();
}
}
throw new IllegalArgumentException("No such Num: " + num
+ " int the AutoNumEnum.");
}
public static String getNumBykey(String key) {
for (AutoNumEnum auto : AutoNumEnum.values()) {
if (auto.getKey().equalsIgnoreCase(key)) {
return auto.getNum();
}
}
throw new IllegalArgumentException("No such Key: " + key
+ " int the AutoNumEnum.");
}
public static void main(String[] args) {
System.out.println(AutoNumEnum.getNumBykey("USERNUM"));
System.out.println(AutoNumEnum.getKeyByNum("110"));
}
}
辅助枚举: