平时写了很多java小代码,删除了可惜,空位请留给有需要的朋友  package test;
/**
 *去除字符串的无效零
*/
public class Test001 {
public static void main(String[] args) {
Test001 test001 = new Test001();
//测试一
String str1 = "00001";
String str1RemoveZero = test001.removeZero(str1);
System.out.println("str1RemoveZero=" + str1RemoveZero);// 1

//测试二
String str2 = "000100000";
String str2RemoveZero = test001.removeZero(str2);
System.out.println("str2RemoveZero=" + str2RemoveZero);// 100000

//测试三
String str3 = "000100000.0010";
String str3RemoveZero = test001.removeZero(str3);
System.out.println("str3RemoveZero=" + str3RemoveZero);// 100000.001

//测试四
String str4 = "000.000100";
String str4RemoveZero = test001.removeZero(str4);
System.out.println("str4RemoveZero=" + str4RemoveZero);// 0.0001

//测试五
String str5 = "000adf100000";
String str5RemoveZero = test001.removeZero(str5);
System.out.println("str5RemoveZero=" + str5RemoveZero);// ""

//从上面的测试结果来看,应该说很好的满足我们的目的了 } /**
 * 将给定的字符串型的数值输入数据中的无效零去掉,返回一个新的字符串。
 * @param str 你要转换的字符串
 * @return  转换后的字符串
 */
public String removeZero(String str) {
String temp = str;
temp = temp.replaceAll("\\.", "").replaceAll("\\d", "");
if (!temp.equals("")) {
//因为出现了非法字符了,所以直接返回 "";
return "";
}
String returnString = str;
//首先判断有没有.
int indexPoint = returnString.indexOf(".");
//如果有.则分为左右两部分处理,左边是整数部分,右边是剩下的部分
if (indexPoint > 0) {
//获取整数部分
String strLeft = returnString.substring(0, indexPoint);
//获取剩下的部分
String strRight = returnString.substring(indexPoint, returnString
.length());
//将整数部分的前缀0都去掉,前提是至少整数部分还有一位
while (strLeft.startsWith("0") && strLeft.length() > 1) {
strLeft = strLeft.substring(1, strLeft.length());
}
//将小数部分的0都去掉,
while (strRight.endsWith("0")) {
strRight = strRight.substring(0, strRight.length() - 1);
}
//如果小数部分全部是0,则小数点.也是没有意思的,则也去掉
if (strRight.endsWith(".")) {
strRight = "";
}
//将处理过的整数部分和剩下的部分再次合起来,连成返回的字符串
returnString = strLeft + strRight;
}
//如果没有小数点,则好办多了,直接将前缀的0去掉,前提是至少整数部分还有一位
else{
while (returnString.startsWith("0") && returnString.length() > 1) {
returnString = returnString.substring(1, returnString.length());
}
}
return returnString;
}
}

解决方案 »

  1.   


    package test;
    /**
     * 查找1000到10000的吸血鬼数字
     * 21*60=1260
     * @author dyw31415926
     *
     */
    public class Xixuegui {
    public static void main(String[] args) {
    Xixuegui xixuegui = new Xixuegui();
    xixuegui.printXixueguiNumber2();
    }
    public void printXixueguiNumber2(){
    String[]   ar_str1,ar_str2;    
            int   sum=0;    
            //双重循环穷举    
            for(int   i=10;i <100;i++){      
                //j=i+1避免重复      
                for(int   j=i+1;j <100;j++){        
                    int   i_val=i*j;        
                    if(i_val <1000 ||i_val >9999)
                        continue;   //积小于1000或大于9999排除,继续下一轮环        
                    ar_str1=String.valueOf(i_val).split("");        
                    ar_str2=(String.valueOf(i)+String.valueOf(j)).split("");        
                    java.util.Arrays.sort(ar_str1);        
                    java.util.Arrays.sort(ar_str2);        
                    if(java.util.Arrays.equals(ar_str1,   ar_str2)){
                        //排序后比较,为真则找到一组            
                        sum++;          
                        System.out.println("第"+sum+"组:   "+i+"*"+j+"="+i_val);        
                    }      
                }    
            }    
            System.out.println("共找到"+sum+"组吸血鬼数");  
    } public void printXixueguiNumber() {
    int i, j, k, a, b, c, d, n, m;
    for (i = 1001; i < 9999; i++) {
    a = i / 1000;
    b = (i - a * 1000) / 100;
    c = (i - a * 1000 - b * 100) / 10;
    d = i - a * 1000 - b * 100 - c * 10;
    if ((c == 0) && (d == 0)) {
    continue;
    } if (i == (a * 10 + b) * (c * 10 + d))
    System.out.println(i + "is xixuegui");
    else if (i == (a * 10 + b) * (d * 10 + c))
    System.out.println(i + "is xixuegui" + (a * 10 + b) + "*"
    + (d * 10 + c));
    else if (i == (b * 10 + a) * (c * 10 + d))
    System.out.println(i + "is xixuegui" + (b * 10 + a) + "*"
    + (c * 10 + d));
    else if (i == (b * 10 + a) * (d * 10 + c))
    System.out.println(i + "is xixuegui" + (b * 10 + a) + "*"
    + (d * 10 + c)); else if (i == (a * 10 + c) * (b * 10 + d))
    System.out.println(i + "is xixuegui" + (a * 10 + c) + "*"
    + (b * 10 + d));
    else if (i == (a * 10 + c) * (d * 10 + b))
    System.out.println(i + "is xixuegui" + (a * 10 + c) + "*"
    + (d * 10 + b));
    else if (i == (c * 10 + a) * (b * 10 + d))
    System.out.println(i + "is xixuegui" + (c * 10 + a) + "*"
    + (b * 10 + d));
    else if (i == (c * 10 + a) * (d * 10 + b))
    System.out.println(i + "is xixuegui" + (c * 10 + a) + "*"
    + (d * 10 + b)); else if (i == (a * 10 + d) * (b * 10 + c))
    System.out.println(i + "is xixuegui" + (a * 10 + d) + "*"
    + (b * 10 + c));
    else if (i == (a * 10 + d) * (c * 10 + b))
    System.out.println(i + "is xixuegui" + (a * 10 + d) + "*"
    + (c * 10 + b));
    else if (i == (d * 10 + a) * (b * 10 + c))
    System.out.println(i + "is xixuegui" + (d * 10 + a) + "*"
    + (b * 10 + c));
    else if (i == (d * 10 + a) * (c * 10 + b))
    System.out.println(i + "is xixuegui" + (d * 10 + a) + "*"
    + (c * 10 + b)); else if (i == (b * 10 + c) * (a * 10 + d))
    System.out.println(i + "is xixuegui" + (b * 10 + c) + "*"
    + (a * 10 + d));
    else if (i == (b * 10 + c) * (d * 10 + a))
    System.out.println(i + "is xixuegui" + (b * 10 + c) + "*"
    + (d * 10 + a));
    else if (i == (c * 10 + b) * (a * 10 + d))
    System.out.println(i + "is xixuegui" + (c * 10 + b) + "*"
    + (a * 10 + d));
    else if (i == (c * 10 + b) * (d * 10 + a))
    System.out.println(i + "is xixuegui" + (c * 10 + b) + "*"
    + (d * 10 + a));
    } }}
      

  2.   


       package com.david.studenttest.database;import java.sql.Connection;
    import java.sql.DriverManager;
    /**
    * 最基本的jdbc连接类,连接sql server2000,注意给sql server2000打上补丁3,补丁4
    */
    public class DBConnection {
    public static String SQLDRIVER  = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
    public static String SQLURL = "jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=stutestdb";
    public static String SQLUSER = "sa";
    public static String SQLPASSWORD = "";
    private Connection conn = null; public Connection getConnection() {
    try {
    Class.forName(SQLDRIVER)
    .newInstance();
    conn = DriverManager.getConnection(SQLURL, SQLUSER,SQLPASSWORD);
    } catch (Exception ex) {
               ex.printStackTrace();
               return null;
    }
    return conn;
    }

    public void closeConn(){
    try{
    if( conn != null){
    conn.close();
    }
    }
    catch(Exception ex){
    ex.printStackTrace();
    }
    }
    }
      

  3.   


       package test;
    /**
     * 对域名的一些处理
     * @author david
     *
     */
    public class TestURL {
       public static void main(String[]args){
       TestURL testURL = new TestURL();
       String str1 = "http://www.blogjava.net/max/";
       String str2 = "http://www.blogjava.net/max";
       String str3 = "http://www.blogjava.net:8080/max/";
       String str4 = "http://www.blogjava.net:8080/max";
       String str5 = "http://www.blogjava.net:8080/";
       String str6 = "http://www.blogjava.net/";
       String str7 = "http://www.blogjava.net";
       String str8 = "https://david.blogjava.com:8080/";
       boolean blstr1 = testURL.isSubDomain(str1);
       System.out.println("blstr1:" + blstr1);
       
       boolean blstr2 = testURL.isSubDomain(str2);
       System.out.println("blstr2:" + blstr2);
       
       boolean blstr3 = testURL.isSubDomain(str3);
       System.out.println("blstr3:" + blstr3);
       
       boolean blstr4 = testURL.isSubDomain(str4);
       System.out.println("blstr4:" + blstr4);
       
       boolean blstr5 = testURL.isSubDomain(str5);
       System.out.println("blstr5:" + blstr5);
       
       boolean blstr6 = testURL.isSubDomain(str6);
       System.out.println("blstr6:" + blstr6);
       
       boolean blstr7 = testURL.isSubDomain(str7);
       System.out.println("blstr7:" + blstr7);
       
       
       System.out.println("==========================================================");
       testURL.remove80port(str8);
       
       testURL.getMaindomainWithout80Port(str8);
       
       
       
       
       }
       public boolean isSubDomain(String domain){
       boolean isSubDomain = false;
       String temp = domain;
       temp = temp.replaceFirst("http(s)?://", "");
       if( temp.endsWith("/")){
       temp = temp.substring(0, temp.length()-1);   
       }
       int indexOfXiegang = temp.indexOf("/");
       if( indexOfXiegang >= 0){
        isSubDomain = true;;
       }
       System.out.println("temp:" + temp);
       return isSubDomain;   }
       
       /**
        * 删除url中的:80端口 和 http(s)?://,默认就是80端口
        * 例子
        * https://www.blogjava.net:80/max/index.html
        * return www.blogjava.net/max/index.html
        * https://www.blogjava.net:8080/max/index.html
        * return www.blogjava.net:8080/max/index.html
        * @param url
        * @return
        */
       public String remove80port(String url){
       String temp = url;
       temp = temp.replaceFirst("http(s)?://", "");
       if( temp.endsWith("/")){
       temp = temp.substring(0, temp.length()-1);   
       }
       int indexXiegang = temp.indexOf("/");
       int indexMaohao = temp.indexOf(":");
       if( indexXiegang >= 0){
       //按子域名的情况处理
       if( indexMaohao >=0){
       String strPort = temp.substring(indexMaohao+1, indexXiegang);
       System.out.println("port:" + strPort);
       if( strPort.equals("80")){
       temp = temp.substring(0, indexMaohao) + temp.substring(indexXiegang, temp.length());
       }
       }
       }
       else
       {
       //按主域名的情况处理
       if( indexMaohao >=0){
       String strPort = temp.substring(indexMaohao+1, temp.length());
       System.out.println("port:" + strPort);
       if( strPort.equals("80")){
       temp = temp.substring(0, indexMaohao) + temp.substring(indexXiegang, temp.length());
       }
       }
       }
       System.out.println("temp:" + temp);
       return temp;
       }
       
       /**
        * 取一个URL中的主域名,带上端口,如果是80端口,则不带端口,默认就是80端口
        * 例子
        * https://www.blogjava.net:80/max/index.html
        * return www.blogjava.net
        * https://www.blogjava.net:8080/max/index.html
        * return www.blogjava.net:8080
        * @param url
        * @return
        */
       public String getMaindomainWithout80Port(String url){
       String temp = url;
       temp = temp.replaceFirst("http(s)?://", "");
       if( temp.endsWith("/")){
       temp = temp.substring(0, temp.length()-1);   
       }
       int indexXiegang = temp.indexOf("/");
       int indexMaohao = temp.indexOf(":");
       if( indexXiegang >=0){
       temp = temp.substring(0, indexXiegang);
       }
       if( indexMaohao >= 0){
       String strPort = temp.substring(indexMaohao+1, temp.length());
       System.out.println("port:" + strPort);
       if( strPort.equals("80")){
       temp = temp.substring(0, indexMaohao);
       }
       }
       System.out.println("temp:" + temp);
       return temp;
       }
       
       
    }
      

  4.   


    package test;//8 Queen 递归算法 
    //如果有一个Q 为 chess[i]=j; 
    //则不安全的地方是 k行 j位置,j+k-i位置,j-k+i位置 class Queen8{ 
    static final int QueenMax = 8; 
    static int oktimes = 0; 
    static int chess[] = new int[QueenMax];//每一个Queen的放置位置 
    public Queen8(){ 
    for (int i=0;i<QueenMax;i++)chess[i]=-1; 
    placequeen(0); 
    System.out.println("八皇后共有"+oktimes+"个解法"); 

    public static void placequeen(int num){ //num 为现在要放置的行数 
    int i=0; 
    boolean qsave[] = new boolean[QueenMax]; 
    for(;i<QueenMax;i++) qsave[i]=true; //下面先把安全位数组完成 
    i=0;//i 是现在要检查的数组值 
    while (i<num){ 
    qsave[chess[i]]=false; 
    int k=num-i; 
    if ( (chess[i]+k >= 0) && (chess[i]+k < QueenMax) ) qsave[chess[i]+k]=false; 
    if ( (chess[i]-k >= 0) && (chess[i]-k < QueenMax) ) qsave[chess[i]-k]=false; 
    i++; 

    //下面历遍安全位 
    for(i=0;i<QueenMax;i++){ 
    if (qsave[i]==false)continue; 
    if (num<QueenMax-1){ 
    chess[num]=i; 
    placequeen(num+1); 

    else{ //num is last one 
    chess[num]=i; 
    oktimes++; 
    System.out.println("这是第"+oktimes+"个解法 如下:"); 
    System.out.println("第n行: 1 2 3 4 5 6 7 8"); for (i=0;i<QueenMax;i++){ 
    String row="第"+(i+1)+"行:"; 
    if (chess[i]==0); 
    else 
    for(int j=0;j<chess[i];j++) row+="--"; 
    row+="++"; 
    int j = chess[i]; 
    while(j<QueenMax-1){row+="--";j++;} 
    System.out.println(row); 



    //历遍完成就停止 
    } public static void main(String args[]){ Queen8 quee8=new Queen8(); } 

      

  5.   


    package test;
    //测试类
    public class TestBox{
    public static void main(String[] args){
    Box box = new Box();

    box.b1(); //打开电源
    box.b2();//按b2 (对应L1)
    box.b3(); //按b3 (对应L2)
    box.b3();  //按b3 (对应L2)
    box.showL1L2Status();
            box.brokenLight1(); //砸烂L1
        box.showL1L2Status();//显示2个灯的状态
        box.b4(); //关灯
        box.showL1L2Status(); //显示2个灯的状态
        box.b1(); //再开灯
        box.showL1L2Status(); //显示2个灯的状态
        box.repairLight(); //关灯,修理灯
        box.showL1L2Status(); //显示2个灯的状态
        box.b1(); //修理后重新打开电源
        box.b2(); 
        box.showL1L2Status();
        
    }
    }
    //盒子类
    class Box {
    private boolean power = false;//电源
    private Light l1 = new Light();//电灯一
    private Light l2 = new Light();//电灯二
       public void b1(){ //开打电源
       power = true;
       l1.setCount(0); //每次重开电源,重新计算L1,L2被按的次数
       l2.setCount(0);
       }
       public void b2(){  //按b2按钮,对应L1
       if( !power){ //如果电源没开,不响应,
       return;
       }
       else{
       this.l1.AddCount();
       //System.out.println("l2:" + l1.getCount());
       if( !checkBroken()){ //只有灯没坏时才响应
       int light1Count = l1.getCount();
       int light2Count = l2.getCount();
       if( light1Count > light2Count){
    l1.setStatus("light");
    l2.setStatus("unlight");
       }
       else {if ( light2Count > light1Count){
       l2.setStatus("light");
       l2.setStatus("unlight");
       }
       else {
       l1.setStatus("unlight");
       l2.setStatus("unlight");
       }}
       }//if(!checkBroken)
       else{  //灯坏了,就不响应
       if( l1.getStatus().equals("broken")){
       l2.setStatus("glimpse");
       }
       else{
       l1.setStatus("glimpse");
       }
       }// checkBroken else 
       }
       } 
       public void b3(){ //参照b2的注释
       if( !power){ 
       return;
       }
       else{
       this.l2.AddCount();
       //System.out.println("l2:" + l2.getCount());
       if( !checkBroken()){
       int light1Count = l1.getCount();
       int light2Count = l2.getCount();
       if( light1Count > light2Count){
    l1.setStatus("light");
    l2.setStatus("unlight");
       }
       else{ if ( light2Count > light1Count){
       l2.setStatus("light");
       l1.setStatus("unlight");
       }
       else {
       l1.setStatus("unlight");
       l2.setStatus("unlight");
       } }
       }//if(!checkBroken)
       else{
       if( l1.getStatus().equals("broken")){
       l2.setStatus("glimpse");
       }
       else{
       l1.setStatus("glimpse");
       }
       }// checkBroken else 
       }
       }
       public void b4(){ //关电源
       power = false;
       //没坏的话,就设置灯为关闭状态,否则保持原来的状态
       if ( (!this.l1.getStatus().equals("broken")) 
       &&(!this.l2.getStatus().equals("broken"))){
       l1.setStatus("unlight");
       l2.setStatus("unlight");
       }
       }  
       //关灯,并将坏的灯泡休息好
    public void repairLight(){
    System.out.println("操作:关电灯,修理");
    b4();
    l1.setStatus("unlight");
    l2.setStatus("unlight");
    }
    //将L1砸烂
    public void brokenLight1(){
    l1.setStatus("broken");
    l2.setStatus("glimpse");
    }
    //将L2砸烂
    public void brokenLight2(){
    l2.setStatus("broken");
    l1.setStatus("glimpse");
    }
    //显示目前灯的状态
    public void showL1L2Status(){
    if(power){
           System.out.println("L1的状态:" + l1.getStatus());
           System.out.println("L2的状态:" + l2.getStatus());
    }
    else{
    System.out.println("L1的状态:unlight");
        System.out.println("L2的状态:unlight");
    }
    }
    //检查是否有灯坏了,有的话返回true,否则返回false
    public boolean checkBroken(){
    boolean flag = false;
    if( l1.getStatus().equals("broken") || l2.getStatus().equals("broken")){
    flag = true;
    }
    return flag;
    }

    }
    //灯泡类
    class Light{
    private String status = "unlight";//状态,从unlight light glimpse broken中选一个
    private int count = 0;
    //被按下按钮的次数+1
    public void AddCount(){
    this.count++;
    }
    //取得被按下的次数
    public int getCount(){
    return this.count;
    }
    //设置被按下的次数
    public void setCount(int count){
    this.count = count;
    }
    //取得灯泡的状态
    public String getStatus(){
    return this.status;
    }
    //设置灯泡的状态
    public void setStatus(String status){
    this.status = status;
    }}
       
      

  6.   


    import   java.awt.image.BufferedImage;
    import   java.io.File;
    import   java.io.IOException;
    import   javax.imageio.ImageIO;
    /**
     *精确切图类
     平时都有经常用到要切1像素或2像素图的需要,又苦于ps不太会(会也不想装,太大了)
    希望有这么一个函数,读入图片(假设图片和类是同一目录下的,如aa.jpg)然后输入4个参数
    左上角坐标0,0,   右下角为   imgwidth,imgheight
    1   横切还是竖切      
    2   从第几个像素(竖切表示从x轴=?,横切表示从y轴=?)开始切    
    3像素条有多少个像素宽(如1px或2px)  
    4   切多长像素
    然后将这部分选种的输出为一个新的jpg(原图是jpg就输入jpg,原图是gif就输入gif)
    做个小使用代码类,方便精确切图。 
     */
    public   class   Picture
    {
    public   static   final   int   SHAFT   =   1,//横
    WANG   =   2;//竖
    public   static   void   newImageFile(File   input,//输入文件
    File   output,//输出文件
    int   model,//横还是竖
    int   begin,//起始像素
    int   width,//宽
    int   length//长
    )   throws   IOException
    {
    BufferedImage   from   =   ImageIO.read(input);//   读入文件
    BufferedImage   subImage;
    if(model   ==   SHAFT)
    subImage   =   from.getSubimage(begin,   0,   width,   length);
    else   if(model   ==   WANG)
    subImage   =   from.getSubimage(0,   begin,   length,   width);
    else
    return;
    ImageIO.write(subImage,   "JPEG",   output);    
    }public   static   void   main(String   args[]){
    File   input   =   new   File("input.jpg");
    File   output1   =   new   File("output1.jpg");
    File   output2   =   new   File("output2.jpg");
    try   {
    newImageFile(input,output1,SHAFT,10,2,20);
    newImageFile(input,output2,WANG,10,2,20);
    }   catch   (IOException   e)   {
    e.printStackTrace();
    }
    }

      

  7.   

     //不知道从哪挖来的了,反正挺好玩的,在firefox下稍微改一下键盘响应事件就好了
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    <HEAD>
    <TITLE> New Document </TITLE>
    <META NAME="Generator" CONTENT="EditPlus">
    <META NAME="Author" CONTENT="">
    <META NAME="Keywords" CONTENT="">
    <META NAME="Description" CONTENT="">
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
    <STYLE>
    .btnup{
             border-left:solid #ffffff 1px;
             border-top:solid #ffffff 1px;
             border-right:solid #828486 1px;
             border-bottom:solid #828486 1px;
       font-size: 9pt;
       cursor:default
            }
    tr{
      font-family:"宋体";
      font-size: 9pt;
      cursor: default
    }
    </STYLE>
    </HEAD>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    var row = 25,col = 25,size=16;
    var delay = 300;//移动延迟
    var paused = false;
    var end = false
    var TimerID;
    var s = new snake();
    var n = new nut();
    var nutad = new Array();
    nutad[0] = -1;
    nutad[1] = -1;
    var Color = new Array(5);
    Color[0] = "#d0d0d0";
    Color[1] = "red";
    Color[2] = "green"
    Color[3] = "blue";
    Color[4] = "yellow";
    var move_direction = new Array();
    var curr_direction = new Array();
    move_direction[0] = 1;
    move_direction[1] = 0;//========================================
    //定义果实
    function nut()
    {
     this.x = -1;
     this.y = -1;
    }function nut_show()
    {
     if (this.x<0 || this.y < 0 )
      return;
     obj = document.all("Main" + this.x + "#" + this.y);
     obj.style.background = Color[2];
    }function nut_create()
    {
     var inx = -1;
     var iny = -1;
     for(;;)
     {
      var cur = true;
      inx = Math.round(Math.random() * (row-1));
      iny = Math.round(Math.random() * (col-1));
      for (var i = 0; i<s.items.length ; i++)
      {
       if (s.items[i].x == inx && s.items[i].y == iny)
       {
        cur = false;
        break;
       }
      }
      if (cur)
      {
       break;
      }
     }
     this.x = inx;
     this.y = iny;
     nutad[0] = inx;
     nutad[1] = iny;
     this.show();
    }function nut_eated()
    {
     if (this.x<0 || this.y < 0)
      return;
     obj = document.all("Main" + this.x + "#" + this.y);
     obj.style.background = Color[0];
    }
    nut.prototype.create = nut_create;
    nut.prototype.show = nut_show;
    nut.prototype.eated = nut_eated;//========================================
    //定义蛇体
    function snake()
    {
     this.items = new Array();
    }function snake_eat(nt)
    {
     var s_length = this.items.length;
     this.items[s_length] = nt;
    }function snake_move(dir)
    {
     this.destroy();
     var y = this.items[0].y;
     var x = this.items[0].x;
     var nx = x + dir[1];
     var ny = y + dir[0];
     if (nx <0 || nx >= row || ny <0 || ny >= col || crossed(nx,ny))
     {
      end = true;
      return;
     }
     caneat(nx,ny);
     for (var i = this.items.length-1 ; i>=0 ; i --)
     {  if (i != 0)
      {
       this.items[i].move(this.items[i-1].x,this.items[i-1].y);
      }
      else
      {
       this.items[i].move(nx,ny);   
      }
     }
     this.reload();
    }function caneat(nx,ny)
    {
     if (nx == nutad[0] && ny == nutad[1])
     {
      var lst = s.items[s.items.length-1];
      var nd = new snakeNode(lst.x,lst.y);
      s.eat(nd);
      n.eated();
      n.create();
     }}
    //禁止穿越自身节点
    function crossed( nx,  ny )
    {
     for (var i = 0; i<s.items.length; i++)
     {
      if (s.items[i].x == nx && s.items[i].y == ny)
      {
       return true;
      }
     }
     return false;
    }function snake_reload()
    {
     for (var i = 0 ; i<this.items.length ; i ++)
     {
      var curNode = this.items[i];
      obj = document.all("Main" + curNode.x + "#" + curNode.y);
      obj.style.background = Color[1];
     }
    }function snake_destroy()
    {
     for (var i = 0 ; i<this.items.length ; i ++)
     {
      var curNode = this.items[i];
      obj = document.all("Main" + curNode.x + "#" + curNode.y);
      obj.style.background = Color[0];
     }
    }function snake_clear()
    {
     this.destroy();
     this.items = new Array();
    }snake.prototype.eat = snake_eat;
    snake.prototype.move = snake_move;
    snake.prototype.reload = snake_reload;
    snake.prototype.destroy = snake_destroy;
    snake.prototype.clear = snake_clear;//蛇体节点
    function snakeNode(x,y)
    {
     this.id = 0;//编号
     this.x = x;//坐标X
     this.y = y;//坐标Y
     this.color = "#000000";
    }function snakeNode_setC(d_color)
    {
     this.color = d_color;
    }function snakeNode_move(dx,dy)
    {
     this.x = dx;
     this.y = dy;
    }snakeNode.prototype.setColor = snakeNode_setC ;
    snakeNode.prototype.move = snakeNode_move ;//========================================
    //程序界面
    //初始化主控制区
    function DrawArea(row,col,name){
     var s = "<TABLE BORDER=1 cellspacing=0 cellpadding=1 bgcolor=" + Color[0] + ">";
     for(var i=0; i<row; i++){
      s = s + "<TR Height=" + size + ">";
      for(var j=0; j<col; j++){
       var id = name + i + "#" + j;
       s = s + "<TD Width=" + size + " class=btnup id=" + id;
       s = s + " style=\"background:" + Color[0] + "\">&nbsp;</TD>"
      }
      s = s + "</TR>";
     }
     s = s + "</TABLE>";
     return s;
    }//初始化
    function Init(){
     MainArea.innerHTML = DrawArea(row,col,'Main');
    }//==================================
    //程序控制区,用来接收输入、定义控制方法
    //控制输入
    function keyDown(){
     switch(event.keyCode)
     {
      case 37:
       if (curr_direction[0] != -1)
       {
       move_direction[0] = -1;
       move_direction[1] = 0;
       }
       break;
      case 38:
       if (curr_direction[1] != -1)
       {
       move_direction[0] = 0;
       move_direction[1] = -1;
       }
       break;
      case 39:
       if (curr_direction[0] != 1)
       {
       move_direction[0] = 1;
       move_direction[1] = 0;
       }
       break;
      case 40:
       if (curr_direction[1] != 1)
       {
       move_direction[0] = 0;
       move_direction[1] = 1;
       }
       break;
     }
    }function Begin()
    {
     end = false;
     paused = false;
     s.clear();
     for (var i = 8; i >=0 ; i--)
     {
      sn = new snakeNode(0,i);
      s.eat(sn);
     }
     n.eated();
     n.create();
     move_direction[0] = 1;
     move_direction[1] = 0;
     curr_direction[1] = s.items[1].x - s.items[0].x;
     curr_direction[0] = s.items[1].y - s.items[0].y;
     Start();
    }//启动开关
    function Start()
    {
     if (end)
     {
      s.reload();
      alert("挂了!");
      return;
     }
     window.clearInterval(TimerID);
     TimerID = window.setInterval("Run()",delay);
    }//运行主体
    var d = true;
    function Run(){
     if(paused) return;
     if(true){
      window.clearInterval(TimerID);
      s.move(move_direction);
      curr_direction[1] = s.items[1].x - s.items[0].x;
      curr_direction[0] = s.items[1].y - s.items[0].y;
      Start();
     }
     }//暂停开关
    function Pause()
    {
     if (paused)
     {
      paused = false;
      if (!end)
      {
       Run();
      }
     }
     else
     {
      paused = true;
     }
    }//结束
    function Over()
    {
     end = true;
    }
    //-->
    </SCRIPT>
    <BODY BGCOLOR="#FFFFFF" onload="Init()" onkeydown="keyDown()" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
    <TABLE border="0" cellspacing="0" cellpadding="0" align="center" width="80%">
      <TR>
    <TR valign="top" width="80%">
     <TD><SPAN ID="MainArea"></SPAN></TD>
     <TD align="center">
      <BUTTON ID="start" onclick="Begin()">Start</BUTTON><br>
      <BUTTON ID="pause" onclick="Pause()">pause</BUTTON><br>
      <BUTTON ID="over" onclick="Over()">End</BUTTON><br>
     </TD>
    </TR>
    </TABLE>
    </BODY>
    </HTML>
      

  8.   

    猜数字游戏,适合初学者练练手,非常简单   import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Random;/**
     * @author david
     * 猜数字游戏
     */
    public class GuessNumber { public static void main(String[] args) {
    // 新建一个随机数产生器,然后生成一个0到99之间的整数
    Random random = new Random();
    int number = random.nextInt(100); // 记录玩家所猜测的数字
    int guess = 0; // 获取控制台输入
    BufferedReader input = new BufferedReader(new InputStreamReader(
    System.in)); // 记录玩家猜测的次数。
    int counter = 0; System.out.println("我心里有一个0到99之间的整数,你猜是什么?"); do {
    try {
    // 获取玩家的输入。
    guess = Integer.parseInt(input.readLine());
    } catch (NumberFormatException e) {
    // 如果玩家不是输入一个合法的整数,则让他重新输入。
    System.out.println("请输入一个0-99之间的整数!");
    continue;
    } catch (IOException e) {
    System.out.println("程序发生异常错误将被关闭!");
    e.printStackTrace();
    } // 对玩家的输入进行判断。
    if (guess > number)
    System.out.println("大了点,再猜!");
    if (guess < number)
    System.out.println("小了点,再试试!"); // 计数器增加一。
    counter++;
    } while (guess != number); // 判断成绩。
    switch (counter) {
    case 1:
    System.out.println("守护……快来看上帝……");
    break;
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    case 7:
    System.out.println("这么快就猜对了,你很聪明啊!");
    break;
    default:
    System.out.println("猜了半天才猜出来,小同志,尚须努力啊!");
    break;
    } System.out.println("Game Over!");
    }
    }
      

  9.   

    import javax.swing.*;import java.awt.*;
    import java.sql.*;
    import java.awt.event.*;public class CheckFrame01 extends JFrame implements ActionListener,KeyListener { JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel(); JLabel label0 = new JLabel("修改信息");
    JLabel label1 = new JLabel("管理员:");
    JLabel label2 = new JLabel("原密码:");
    JLabel label3 = new JLabel("新密码:"); JTextField text1 = new JTextField(10);
    JPasswordField text2 = new JPasswordField(10);
    JPasswordField text3 = new JPasswordField(10); JButton bt1 = new JButton("修改");
    JButton bt2 = new JButton("取消");
    public CheckFrame01() {

    super("修改管理");
    this.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 20));
    this.getContentPane().setBackground(Color.orange);
    label0.setFont(new Font("楷体",0,30));
    this.getContentPane().add(label0);
    this.getContentPane().add(panel1);
    this.getContentPane().add(panel2);
    panel1.setBackground(Color.orange);
    panel2.setBackground(Color.orange); panel1.setLayout(new GridLayout(4, 2)); panel1.add(label3, 2, 0);
    panel1.add(text3, 2, 1); panel1.add(label2, 1, 0);
    panel1.add(text2, 1, 1); panel1.add(label1, 0, 0);
    panel1.add(text1, 0, 1); panel2.add(bt1, 0, 0);
    panel2.add(bt2, 0, 1); bt1.addActionListener(this);
    bt2.addActionListener(this); bt1.addKeyListener(this);
    bt2.addKeyListener(this);
    }
    public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if (e.getSource() == bt1) {
    JOptionPane jopt = new JOptionPane();// 修改密码响应事件
    Connection conn = null;
    try {
    Class.forName("com.mysql.jdbc.Driver");
    String url = "jdbc:mysql://localhost:3306/test";
    String username = "root";
    String password = "root";
    conn = DriverManager.getConnection(url, username, password);
    Statement stamente = conn.createStatement();
    String sql = "select * from passwordbiao where PRO_PASSWORD='"
    + text2.getText() + "' and PRO_NAME='"
    + text1.getText() + "'";
    ResultSet rs = stamente.executeQuery(sql);
    if (rs.next()) {
    jopt.showMessageDialog(null, "密码修改成功!", "修改成功",
    jopt.INFORMATION_MESSAGE);
    this.dispose();
    stamente
    .executeUpdate("Update passwordbiao set PRO_PASSWORD='"
    + text3.getText()
    + "'where PRO_NAME='"
    + text1.getText() + "'");
    } else {
    jopt.showMessageDialog(null, "密码修改失败!", "修改失败",
    jopt.INFORMATION_MESSAGE);
    }
    conn.close();
    rs.close(); } catch (ClassNotFoundException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    } catch (SQLException e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
    }
    }
    if (e.getSource() == bt2) {
    dispose();
    }
    } @Override
    public void keyPressed(KeyEvent e) {
    // TODO Auto-generated method stub
    if (e.getSource() == bt1) {
    JOptionPane jopt = new JOptionPane();// 修改密码响应事件
    Connection conn = null;
    try {
    Class.forName("com.mysql.jdbc.Driver");
    String url = "jdbc:mysql://localhost:3306/test";
    String username = "root";
    String password = "root";
    conn = DriverManager.getConnection(url, username, password);
    Statement stamente = conn.createStatement();
    String sql = "select * from passwordbiao where PRO_PASSWORD='"
    + text2.getText() + "' and PRO_NAME='"
    + text1.getText() + "'";
    ResultSet rs = stamente.executeQuery(sql);
    if (rs.next()) {
    jopt.showMessageDialog(null, "密码修改成功!", "修改成功",
    jopt.INFORMATION_MESSAGE);
    this.dispose();
    stamente
    .executeUpdate("Update passwordbiao set PRO_PASSWORD='"
    + text3.getText()
    + "'where PRO_NAME='"
    + text1.getText() + "'");
    } else {
    jopt.showMessageDialog(null, "密码修改失败!", "修改失败",
    jopt.INFORMATION_MESSAGE);
    }
    conn.close();
    rs.close(); } catch (ClassNotFoundException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    } catch (SQLException e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
    }
    }
    if (e.getSource() == bt2) {
    dispose();
    }

    } @Override
    public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub

    } @Override
    public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

    }}各位神人 帮我解决一下 我想添加 键盘响应事件 啊