public static void main(String args[])
{
Element element=null;
File f =new File("a.xml");
DocumentBuilder db=null; //documentBuilder为抽象不能直接实例化(将XML文件转换为DOM文件)
DocumentBuilderFactory dbf=null;
try{
dbf= DocumentBuilderFactory.newInstance(); //返回documentBuilderFactory对象
db =dbf.newDocumentBuilder();//返回db对象用documentBuilderFatory对象获得返回documentBuildr对象
Document dt= db.parse(f); //得到一个DOM并返回给document对象
element = dt.getDocumentElement();//得到一个elment根元素
public class JDBConnection {
public Connection conn = null; // 声明Connection对象的实例
public Statement stmt = null; // 声明Statement对象的实例
public ResultSet rs = null; // 声明ResultSet对象的实例
public static String dateSub(int dateKind, String dateStr, int amount) {
Date date = stringtoDate(dateStr, FORMAT_ONE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(dateKind, amount);
return dateToString(calendar.getTime(), FORMAT_ONE);
}
/**
* 两个日期相减
* @return 相减得到的秒数
*/
public static long timeSub(String firstTime, String secTime) {
long first = stringtoDate(firstTime, FORMAT_ONE).getTime();
long second = stringtoDate(secTime, FORMAT_ONE).getTime();
return (second - first) / 1000;
}
/**
* 获得某月的天数
*/
public static int getDaysOfMonth(String year, String month) {
int days = 0;
if (month.equals("1") || month.equals("3") || month.equals("5")
|| month.equals("7") || month.equals("8") || month.equals("10")
|| month.equals("12")) {
days = 31;
} else if (month.equals("4") || month.equals("6") || month.equals("9")
|| month.equals("11")) {
days = 30;
} else {
if ((Integer.parseInt(year) % 4 == 0 && Integer.parseInt(year) % 100 != 0)
|| Integer.parseInt(year) % 400 == 0) {
days = 29;
} else {
days = 28;
}
}
return days;
}
/**
* 获取某年某月的天数
*/
public static int getDaysOfMonth(int year, int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, 1);
return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* 获得当前日期
*/
public static int getToday() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.DATE);
}
/**
* 获得当前月份
*/
public static int getToMonth() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.MONTH) + 1;
}
/**
* 获得当前年份
*/
public static int getToYear() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.YEAR);
}[/code]作者: 匿名 时间: 2011-8-2 15:22
接上[code] /**
* 返回日期的天
*/
public static int getDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DATE);
}
/**
* 返回日期的年
*/
public static int getYear(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
/**
* 返回日期的月份,1-12
*/
public static int getMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH) + 1;
}
/**
* 计算两个日期相差的天数,如果date2 > date1 返回正数,否则返回负数
*/
public static long dayDiff(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / 86400000;
}
/**
* 比较两个日期的年差
*/
public static int yearDiff(String before, String after) {
Date beforeDay = stringtoDate(before, LONG_DATE_FORMAT);
Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
return getYear(afterDay) - getYear(beforeDay);
}
/**
* 比较指定日期与当前日期的差
*/
public static int yearDiffCurr(String after) {
Date beforeDay = new Date();
Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
return getYear(beforeDay) - getYear(afterDay);
}
/**
* 比较指定日期与当前日期的差
*/
public static long dayDiffCurr(String before) {
Date currDate = DateUtil.stringtoDate(currDay(), LONG_DATE_FORMAT);
Date beforeDate = stringtoDate(before, LONG_DATE_FORMAT);
return (currDate.getTime() - beforeDate.getTime()) / 86400000;
}
/**
* 获取每月的第一周
*/
public static int getFirstWeekdayOfMonth(int year, int month) {
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
c.set(year, month - 1, 1);
return c.get(Calendar.DAY_OF_WEEK);
}
/**
* 获取每月的最后一周
*/
public static int getLastWeekdayOfMonth(int year, int month) {
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
c.set(year, month - 1, getDaysOfMonth(year, month));
return c.get(Calendar.DAY_OF_WEEK);
}
/**
* 获得当前日期字符串,格式"yyyy_MM_dd_HH_mm_ss"
*
* @return
*/
public static String getCurrent() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
StringBuffer sb = new StringBuffer();
sb.append(year).append("_").append(StringUtil.addzero(month, 2))
.append("_").append(StringUtil.addzero(day, 2)).append("_")
.append(StringUtil.addzero(hour, 2)).append("_").append(
StringUtil.addzero(minute, 2)).append("_").append(
StringUtil.addzero(second, 2));
return sb.toString();
}
public String[] CreateHCode() {// 根据哈夫曼树求哈夫曼编码
int n = charsAndWeight.length;
int i, f, c;
String hcodeString = "";
hcs = new String[n];
for (i = 0; i < n; i++) {// 根据哈夫曼树求哈夫曼编码
c = i;
hcodeString = "";
f = hfmcoding[i][1]; // f 哈弗曼树的根节点
while (f != 0) {// 循序直到树根结点
if (hfmcoding[f][2] == c) {// 处理左孩子结点
hcodeString += "0";
} else {
hcodeString += "1";
}
c = f;
f = hfmcoding[f][1];
}
hcs[i] = new String(new StringBuffer(hcodeString).reverse());
}
return hcs;
}
public String show(String s) {// 对字符串显示编码
String textString = "";
char c[];
int k = -1;
c = new char[s.length()];
c = s.toCharArray();// 将字符串转化为字符数组
for (int i = 0; i < c.length; i++) {
k = c[i];
for (int j = 0; j < charsAndWeight.length; j++)
if (k == charsAndWeight[j][0])
textString += hcs[j];
}
return textString;
}
// 哈弗曼编码反编译
public String reCoding(String s) {
String text = "";// 存放反编译后的字符
int k = 0, m = hfmcoding.length - 1;// 从根节点开始查询
char c[];
c = new char[s.length()];
c = s.toCharArray();
k = m;
for (int i = 0; i < c.length; i++) {
if (c[i] == '0') {
k = hfmcoding[k][2];// k的值为根节点左孩子的序号
if (hfmcoding[k][2] == 0 && hfmcoding[k][3] == 0)// 判断是不是叶子节点,条件(左右孩子都为零)
{
text += (char) charsAndWeight[k][0];
k = m;
}
}
if (c[i] == '1') {
k = hfmcoding[k][3];// k的值为根节点右孩子的序号
if (hfmcoding[k][2] == 0 && hfmcoding[k][3] == 0)// 判断是不是叶子节点,条件(左右孩子都为零)
{
text += (char) charsAndWeight[k][0];
k = m;
}
public class Tsp {
private String cityName[]={"北京","上海","天津","重庆","哈尔滨","长春","沈阳","呼和浩特","石家庄","太原","济南","郑州","西安","兰州","银川","西宁","乌鲁木齐","合肥","南京","杭州","长沙","南昌","武汉","成都","贵州","福建","台北","广州","海口","南宁","昆明","拉萨","香港","澳门"};
//private String cityEnd[]=new String[34];
private int cityNum=cityName.length; //城市个数
private int popSize = 50; //种群数量
private int maxgens = 20000; //迭代次数
private double pxover = 0.8; //交叉概率
private double pmultation = 0.05; //变异概率
private long[][] distance = new long[cityNum][cityNum];
private int range = 2000; //用于判断何时停止的数组区间
private class genotype {
int city[] = new int[cityNum]; //单个基因的城市序列
long fitness; //该基因的适应度
double selectP; //选择概率
double exceptp; //期望概率
int isSelected; //是否被选择
}
private genotype[] citys = new genotype[popSize];
/**
* 构造函数,初始化种群
*/
public Tsp() {
for (int i = 0; i < popSize; i++) {
citys[i] = new genotype();
int[] num = new int[cityNum];
for (int j = 0; j < cityNum; j++)
num[j] = j;
int temp = cityNum;
for (int j = 0; j < cityNum; j++) {
int r = (int) (Math.random() * temp);
citys[i].city[j] = num[r];
num[r] = num[temp - 1];
temp--;
}
citys[i].fitness = 0;
citys[i].selectP = 0;
citys[i].exceptp = 0;
citys[i].isSelected = 0;
}
initDistance();
}
/**
* 填充,将多选的填充到未选的个体当中
*/
public void pad(){
int best = 0;
int bad = 0;
while(true){
while(citys[best].isSelected <= 1 && best<popSize-1)
best ++;
while(citys[bad].isSelected != 0 && bad<popSize-1)
bad ++;
for(int i = 0; i< cityNum; i++)
citys[bad].city[i] = citys[best].city[i];
citys[best].isSelected --;
citys[bad].isSelected ++;
bad ++;
if(best == popSize ||bad == popSize)
break;
}
}
/**
* 交叉主体函数
*/
public void crossover() {
int x;
int y;
int pop = (int)(popSize* pxover /2);
while(pop>0){
x = (int)(Math.random()*popSize);
y = (int)(Math.random()*popSize);
executeCrossover(x,y);//x y 两个体执行交叉
pop--;
}
}
/**
* 执行交叉函数
* @param 个体x
* @param 个体y
* 对个体x和个体y执行佳点集的交叉,从而产生下一代城市序列
*/
private void executeCrossover(int x,int y){
int dimension = 0;
for( int i = 0 ;i < cityNum; i++)
if(citys[x].city[i] != citys[y].city[i]){
dimension ++;
}
int diffItem = 0;
double[] diff = new double[dimension];
/**
* 计算选择概率
*/
private void CalSelectP(){
long sum = 0;
for( int i = 0; i< popSize; i++)
sum += citys[i].fitness;
for( int i = 0; i< popSize; i++)
citys[i].selectP = (double)citys[i].fitness/sum;
/**
* 算法执行
*/
public void run(){
long[] result = new long[range];
//result初始化为所有的数字都不相等
for( int i = 0; i< range; i++)
result[i] = i;
int index = 0; //数组中的位置
int num = 1; //第num代
while(maxgens>0){
System.out.println("----------------- 第 "+num+" 代 -------------------------");
CalAll();
print();
pad();
crossover();
mutate();
maxgens --;
long temp = citys[0].fitness;
for ( int i = 1; i< popSize; i++)
if(citys[i].fitness<temp){
temp = citys[i].fitness;
}
System.out.println("最优的解:"+temp);
result[index] = temp;
if(isSame(result))
break;
index++;
if(index==range)
index = 0;
num++;
}
printBestRoute();
}
/**
* @param a 开始时间
* @param b 结束时间
*/
public void CalTime(Calendar a,Calendar b){
long x = b.getTimeInMillis() - a.getTimeInMillis();
long y = x/1000;
x = x - 1000*y;
System.out.println("算法执行时间:"+y+"."+x+" 秒");
}
/**
* 程序入口
*/
public static void main(String[] args) {
Calendar a = Calendar.getInstance(); //开始时间
Tsp tsp = new Tsp();
tsp.run();
Calendar b = Calendar.getInstance(); //结束时间
tsp.CalTime(a, b);
}
}[/code]作者: 匿名 时间: 2011-8-2 15:42
java 字符串解析[code]StringTokenizer tokenizer = new StringTokenizer(number, ",");
boolean bool = true;
while (tokenizer.hasMoreTokens()) {
try {
Double.valueOf(tokenizer.nextToken());
} catch (Exception e) {
bool = false;
}
}
//将字符串转化为数组的方法
int gv[];
int i = 0;
StringTokenizer tokenizer = new StringTokenizer(goodsVolume, ",, ");
gv = new int[tokenizer.countTokens()];//动态的决定数组的长度
while (tokenizer.hasMoreTokens()) {
String d = tokenizer.nextToken();
gv[i] = Integer.valueOf(d);//将字符串转换为整型
i++;
}
//字符串解析
private String[] stringAnalytical(String str, String divisionChar) {
String string[];
int i = 0;
StringTokenizer tokenizer = new StringTokenizer(str, divisionChar);
string = new String[tokenizer.countTokens()];// 动态的决定数组的长度
while (tokenizer.hasMoreTokens()) {
string[i] = new String();
string[i] = tokenizer.nextToken();
i++;
}
return string;// 返回字符串数组
}