Java经典算法题(1)

1. Java 的 16 进制与字符串的相互转换函数

/**
        * 将指定 byte 数组以 16 进制的形式打印到控制台
 * @param hint String
 * @param b byte[]
 * @return void
*/
public static void printHexString(String hint, byte[] b) {
    System.out.print(hint);
    for (int i = 0; i < b.length; i++) {
        String hex = Integer.toHexString(b[i] & 0xFF);
        if (hex.length() == 1) {
            hex = '0' + hex;
        }
        System.out.print(hex.toUpperCase() + " ");
    }
    System.out.println("");
}
/**
*
* @param b byte[]
* @return String
*/
public static String Bytes2HexString(byte[] b) {
    String ret = "";
    for (int i = 0; i < b.length; i++) {
        String hex = Integer.toHexString(b[i] & 0xFF);
        if (hex.length() == 1) {
            hex = '0' + hex;
        }
        ret += hex.toUpperCase();
    }
    return ret;
}
/**
* 将两个 ASCII 字符合成一个字节;
* 如:"EF"--> 0xEF
* @param src0 byte
* @param src1 byte
* @return byte
*/
public static byte uniteBytes(byte src0, byte src1) {
    byte _b0 = byte.decode("0x" + new String(new byte[]{src0})).byteValue();
    _b0 = (byte)(_b0 << 4);
    byte _b1 = byte.decode("0x" + new String(new byte[]{src1})).byteValue();
    byte ret = (byte)(_b0 ^ _b1);
    return ret;
}
/**
* 将指定字符串 src,以每两个字符分割转换为 16 进制形式
* 如:"2B44EFD9" --> byte[]{0x2B, 0x44, 0xEF, 0xD9}
* @param src String
* @return byte[]
               */
public static byte[] HexString2Bytes(String src){
    byte[] ret = new byte[8];
    byte[] tmp = src.getBytes();
    for (int i=0; i<8; i++){
        ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]);
    }
    return ret;
}

2. JAVA 时间格式化处理

import java.util.Date;
import java.text.SimpleDateFormat;
class dayTime
{
    public static void main(String args[])
    {
        Date nowTime=new Date();
        System.out.println(nowTime);
        SimpleDateFormat time=new SimpleDateFormat("yyyy MM dd HH mm ss");
        System.out.println(time.format(nowTime));
    }
}

3. 将毫秒转化为日期

public static void main(String[] args) {
    new ConvertLong2Date().launchFrame();
}
public String convertL2D(long l) {
    long _l = 0L;
    Date _d = null;
    SimpleDateFormat _sdf = null;
    String _s = null;
    _l = l;
    _d = new Date(_l);
    _sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    _s = _sdf.format(_d);
    return _s;
}

4. 文本的倒序输出

文件 before:
Hello
World
要求输出文件 after:
World
Hello
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.ListIterator;
public class ReverseOrder extends ArrayList {
    public static String read(String fileName) throws IOException {
        StringBuffer sb = new StringBuffer();
        LinkedList lines = new LinkedList();
        BufferedReader in = new BufferedReader(new FileReader(fileName));
        String s;
        while ((s = in.readLine()) != null)
        lines.add(s);
        in.close();
        ListIterator it = lines.listIterator(lines.size());
        while (it.hasPrevious()) {
            sb.append(it.previous());
            sb.append("n");
}
return sb.toString();
}
public static void write(String fileName, String text) throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(
fileName)));
out.print(text);
out.close();
}
public ReverseOrder(String fileName) throws IOException { super(Arrays.asList(read(fileName).split("n")));
}
public void write(String fileName) throws IOException {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter( fileName)));
for (int i = 0; i < size(); i++)
out.println(get(i));
out.close();
}
public static void main(String[] args) throws Exception { String fileName = "e:\1124\before.txt";
ReverseOrder text = new ReverseOrder(fileName);
text.write("e:\1124\after.txt");
}
/*
* 最后会多一个空行,手工删除一下
*/
}

5. 判断一个数字是奇数还是偶数

判断一个数是否是奇数:
public static Boolean isOdd(int i) {
    return (i&1) != 0;
}
判断一个数是否是偶数
public static Boolean isEven(int i) {
    return (i&1) = 0;
}

6. 用Hibernate 实现分页

public List queryByStatus(int status, int currentPage, int lineSize)
throws Exception {
    List all = null;
    String hql = "FROM Question AS q WHERE q.status=? ORDER BY q.questiontime desc";
    Query q = super.getSession().createQuery(hql);
    q.setInteger(0, status);
    q.setFirstResult((currentPage - 1) * lineSize);
    q.setMaxResults(lineSize);
    all = q.list();
    return all;
}

7. 35 选 7 彩票程序

public class caipiao
{
    static void generate()
    {
        int a[]=new int[7];
        int i,m,j;
        fan:for (j=0;j <7;j++){
            //外循环实现随机生成每组 7 个数
            a[j]=(int)(Math.random()*35+1);
            m=a[j];
            if(j>=1){
                for (i=0;i <j;i++)//内循环实现无重复
                if(a[i]==m){
                    j--;
                    continue fan;
                }
            }
            if(a[j] <10)
            System.out.print("0"+a[j]+"  "); else
            System.out.print(a[j]+"  ");
        }
    }
    public static void main (String args[]){
        int n=Integer.parseint(args[0]);
        System.out.println("中国福利彩票 35 选 7");
        for (int i=0;i <n;i++){
            //循环调用方法实现输出 n 组数
            generate();
            System.out.println();
        }
    }
}

8. 获取 GMT8 时间

/**
* Description: 获取 GMT8 时间
* @return 将当前时间转换为 GMT8 时区后的 Date */
public static Date getGMT8Time(){
    Date gmt8 = null;
    try {
        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"),Locale.CHINESE);
        Calendar day = Calendar.getInstance();
        day.set(Calendar.YEAR, cal.get(Calendar.YEAR));
        day.set(Calendar.MONTH, cal.get(Calendar.MONTH));
        day.set(Calendar.DATE, cal.get(Calendar.DATE));
        day.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY));
        day.set(Calendar.MINUTE, cal.get(Calendar.MINUTE));
        day.set(Calendar.SECOND, cal.get(Calendar.SECOND));
        gmt8 = day.getTime();
    }
    catch (Exception e) {
        System.out.println("获取 GMT8 时间 getGMT8Time() error !");
        e.printStackTrace();
        gmt8 = null;
    }
    return  gmt8;
}

9. 中文乱码转换

public String china(String args)
{
    String s=null;
    String s=new String(args.getBytes("ISO-8859-1"),"gb2312");
    return s;
}

10. 小标签

import java.io.IOException;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import com.formcontent.show.ShowFormTypeOperateDb;
import com.forum.hibernatePrj.Space;
public class OutPrintForumType extends TagSupport{
    public int doStartTag() throws JspException
    {
        String printStr="";
        ShowFormTypeOperateDb showtype=new ShowFormTypeOperateDb();
        List list=showtype.getForumType();
        if(list!=null&&list.size()>0)
        {
            for (int i=0;i <list.size();i++)
            {
                Space space=(Space)list.get(i);
                if(space!=null)
                {
                    printStr+=" <tr> <td>"+" <div align='left' class='TypeCss'>"+
                    space.getSpaceName()+" "+space.getSpaceDescription()+" <br/>目前登陆总人数:"+i+" 人访问数:"+i+"人 </div> </td> </tr>"
                    +" <tr> <td> </td> </tr>";
                }
            }
        }
        try {
            pageContext.getOut().write(printStr);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return super.doStartTag();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值