对学习JAVA初学者,简单代码

一个简单的Java应用程序
public class Hello
{
    public static void main (String args[ ])
    {
       System.out.println("
这是一个简单的应用程序");
    }
}


源程序
public class People
{
    float hight,weight;
    String head,ear,mouth;
    void speak(String s)
    {
       System.out.println(s);
    }
}
class A
{
    public static void main(String args[])
    {
      People zhubajie;
      zhubajie=new People();
      zhubajie.weight=200f;    
      zhubajie.hight=1.70F;
      zhubajie.head="
大头";
      zhubajie.ear="
两只大耳朵";
      zhubajie.mouth="
一只大嘴";
      System.out.println("
重量"+zhubajie.weight+"身高" +zhubajie.hight);
      System.out.println(zhubajie.head+zhubajie.mouth+zhubajie.ear);
      zhubajie.speak("
师傅,咱们别去西天了,改去月宫吧");
    }
}


一个简单的Java小应用程序(Java Applet
import java.applet.*;
import java.awt.*;
public class boy extends Applet
{  
    public void paint(Graphics g)
    {
     g.setColor(Color.red);  
     g.drawString("
我一边喝着咖啡,一边学Java",2,30);
     g.setColor(Color.blue);
     g.drawString("
我学得很认真",10,50);
    }
}    


基本数据类型和数组
例子1
public class  Example2_1
{  
    public static void main (String args[ ])
    {
     char chinaWord='
',japanWord='';
     int  p1=20328,p2=12358;
     System.out.println("
汉字/'/'字在unicode表中的顺序位置:"+(int)chinaWord);
     System.out.println("
日语/'/'字在unicode表中的顺序位置:"+(int)japanWord);
     System.out.println("unicode
表中第20328位置上的字符是:"+(char)p1);
     System.out.println("unicode
表中第12358位置上的字符是:"+(char)p2);
    }
}

例子2
public class Example2_2
{
    public static void main (String args[ ])
    {
      byte  a=120;
      short b=255;
      int c=2200;
      long d=8000;
      float f;
      double g=123456789.123456789;
      b=a;
      c=(int)d;
      f=(float)g;   //
导致精度的损失.
      System.out.print("a=  "+a);  
      System.out.println(" b=  "+b);
      System.out.print("  c=  "+c);    
      System.out.println("  d=  "+d);
      System.out.println("f=  "+f);  
      System.out.println("g=  "+g);
    }
}

例子3
public class Example2_3
{
    public static void main(String args[])
    {
     int a[]={1,2,3,4};
     int b[];
     System.out.println(a[3]);
     b=a;
     b[3]=100;
     System.out.println(a[3]);
     System.out.println(b[3]);
    }
}  
运行结果:
4
100
100


运算符、表达式和语句
例子1
class Example3_1
{  
    public static void main(String args[])
    {
      char a1='
',a2='',a3='',a4='';
      char secret='8';
      a1=(char)(a1^secret);  
      a2=(char)(a2^secret);
      a3=(char)(a3^secret);  
      a4=(char)(a4^secret);
      System.out.println("
密文:"+a1+a2+a3+a4);
      a1=(char)(a1^secret);  
      a2=(char)(a2^secret);
      a3=(char)(a3^secret);  
      a4=(char)(a4^secret);
      System.out.println("
原文:"+a1+a2+a3+a4);
    }
}

例子2
class Example3_2
{
    public static void main(String args[])
    {
      float x=12.56f,y;
      if(x<=0)
      {
        y=x+1;
      }
      else if(x>0&&x<=16)
      {
        y=2*x+1;
      }
      else
      {
         y=3*x+3;
      }
      System.out.println(y);
    }
}

例子3
import java.applet.*;
import java.awt.*;
public class Example3_3 extends Applet
{
    public void paint(Graphics g)
    {
      int x=2,y=1;
      switch(x+y)
        {
         case 1 :
             g.setColor(Color.red);g.drawString("i am 1",5,10);
             break;    
         case 2:
             g.setColor(Color.blue); g.drawString("i am 2",5,10);
             break;  
         case 3:  
            g.setColor(Color.green); g.drawString("i am 3",5,10);
            break;    
         default:  g.drawString("
没有般配的",5,10);
        }
    }
}  

例子4
import java.applet.*;
import java.awt.*;
public class Example3_4  extends Applet
{  
    public void paint(Graphics g)
    {  
      int sum=0;
      for(int i=1;i<=100;i++)
        {
           sum=sum+i;
        }
      g.drawString("sum= "+sum,10,20);
    }
}

例子5
class Example3_5
{  
    public static void main(String args[])
    { double sum=0,a=1;int i=1;
      while(i<=20)
        {
          a=a*(1.0/i);
          sum=sum+a;
          i=i+1;          
        }
      System.out.println("sum="+sum);
    }
}

例子 6
class Example3_6
{  
    public static void main(String args[])
    {
       int sum=0,i,j;
       for( i=1;i<=10;i++)                  //
计算1+3+5+7+9
       {  if(i%2==0)
          {
             continue;  
          }
          else
             {}
          sum=sum+i;
       }
       System.out.println("sum="+sum);
    }
}

例子 7
class Example3_7
{  
    public static void main(String args[])
    {
      int n=23,start,end,middle;
      int a[]={-2,1,4,5,8,12,17,23,45,56,90,100};
      start=0;
      end=a.length;
      middle=(start+end)/2;
      int count=0;
      while(n!=a[middle])
        {
          if(n>a[middle])
            {
              start=middle;
            }
          else if(n<a[middle])
            {
              end=middle;
            }
          middle=(start+end)/2;
          count++;
          if(count>a.length/2)
             break;
         }
      if(count>a.length/2)
         System.out.println(":"+n+"
不在数组中");
      else
         System.out.println(":"+n+"
是数组中的第"+middle+"个元素");
    }
}


类、对象、和接口
例子1
class XiyoujiRenwu  
{  
    float height,weight;
    String head, ear,hand,foot, mouth;
    void speak(String s)
    {
       System.out.println(s);
    }
}
class A
{  
    public static void main(String args[])
    {
       XiyoujiRenwu  zhubajie;       //
声明对象。
       zhubajie=new  XiyoujiRenwu(); //
为对象分配内存,使用new 运算符和默认的构造方法。
    }
}

例子2
class Point
{
    int x,y;
    Point(int a,int b)
    {
       x=a;
       y=b;
    }
}
public class A
{
    public static void main(String args[])
    {
      Point p1,p2;                 //
声明对象p1p2
      p1=new Point(10,10);         //
为对象分配内存,使用 new 和类中的构造方法。
      p2=new Point(23,35);        //
为对象分配内存,使用 new 和类中的构造方法。
    }
}

例子3
class XiyoujiRenwu
{
    float height,weight;
    String head, ear,hand,foot,mouth;
    void speak(String s)
    {
       head="
歪着头";
       System.out.println(s);
    }
}
public class Example
{  
    public static void main(String args[])
    {
         XiyoujiRenwu  zhubajie,sunwukong;//
声明对象。
         zhubajie=new  XiyoujiRenwu();  //
为对象分配内存,使用new 运算符和默认的构造方法。
         sunwukong=new  XiyoujiRenwu();
         zhubajie.height=1.80f;                                //
对象给自己的变量赋值。
         zhubajie.weight=160f;      
         zhubajie.hand="
两只黑手";
         zhubajie.foot="
两只大脚";
         zhubajie.head="
大头";
         zhubajie.ear="
一双大耳朵";
         zhubajie.mouth="
一只大嘴";
         sunwukong.height=1.62f;                                //
对象给自己的变量赋值。
         sunwukong.weight=1000f;    
         sunwukong.hand="
白嫩小手";
         sunwukong.foot="
两只绣脚";
         sunwukong.head="
绣发飘飘";
         sunwukong.ear="
一对小耳";  
         sunwukong.mouth="
樱桃小嘴";
         System.out.println("zhubajie
的身高:"+zhubajie.height);
         System.out.println("zhubajie
的头:"+zhubajie.head);
         System.out.println("sunwukong
的重量:"+sunwukong.weight);
         System.out.println("sunwukong
的头:"+sunwukong.head);
         zhubajie.speak("
俺老猪我想娶媳妇");                       //对象调用方法。
         System.out.println("zhubajie
现在的头:"+zhubajie.head);
         sunwukong.speak("
老孙我重1000斤,我想骗八戒背我");         //对象调用方法。
         System.out.println("sunwukong
现在的头:"+sunwukong.head);
    }
}


例子4
class

{  
    double
半径;
    
(double r)
    {
      
半径=r;
     }
    double
计算面积()
    {  
       return 3.14*
半径*半径;
    }
    void
修改半径(double 新半径)
    {  
      
半径=新半径;
    }
    double
获取半径()
    {
        return
半径;
    }
}


class
圆锥
{
    
底圆;
    double
;
    
圆锥( circle,double h)
    {  
       this.
底圆=circle;
       this.
=h;
    }
    double
计算体积()
   {  
       double volume;
       volume=
底圆.计算面积()*/3.0;
       return  volume;
    }
    void
修改底圆半径(double r)
    {  
        
底圆.修改半径(r);
    }
    double
获取底圆半径()
    {  
        return
底圆.获取半径();
    }
}


class Example
{  
    public static void main(String args[])
    {
      
circle=new (10);
      
圆锥 circular=new 圆锥(circle,20);
       System.out.println("
圆锥底圆半径:"+circular.获取底圆半径());
       System.out.println("
圆锥的体积:"+circular.计算体积());
       circular.
修改底圆半径(100);
       System.out.println("
圆锥底圆半径:"+circular.获取底圆半径());
       System.out.println("
圆锥的体积:"+circular.计算体积());  
    }
}


例子5
class
梯形
{  
    float
上底,;
    static float
下底;                //类变量。
    
梯形(float 上底,float )
    {
       this.
上底=上底;
       this.
=;
    }
    float
获取上底()
    {  
       return
上底;
    }
    float
获取下底()
    {  
       return
下底;
    }
}

class Example4_5
{  
    public static void main(String args[])
    {
      
梯形 laderOne,laderTwo;                    //梯形的字节码被加载到内存。
      
梯形.下底=60;                              //通过类名操作类变量。
       laderOne=new
梯形(18.0f,20);
       laderTwo=new
梯形(9.0f,10);
       System.out.println("laderOne
的上底:"+laderOne.获取上底());
       System.out.println("laderOne
的下底:"+laderOne.获取下底());
       System.out.println("laderTwo
的上底:"+laderTwo.获取上底());
       System.out.println("laderTwo
的下底:"+laderTwo.获取下底());
    }
}

例子6
package tom.jiafei;
public class  Example4_6
{  
    public static void main(String args[])
    {
       System.out.println("
我有包名");  
    }
}


例子7
import java.applet.Applet;
import java.awt.*;
public class Example extends Applet
{  
    Button redbutton;
    public void init()
    {  
         redbutton=new Button("
我是一个红色的按钮");
         redbutton.setBackground(Color.red);
         add(redbutton);
    }
    public void  paint(Graphics g)
    {  
         g.drawString("it is a button",30,50);
    }
}


例子8
import tom.jiafei.*;
class Example4_8
{  
    public static void main(String args[])
    {  
        Trangle trangle=new Trangle(12,3,1);
              trangle.
计算面积();
              trangle.
修改三边(3,4,5);
              trangle.
计算面积();
    }
}


例子9
class Example4_9
{  
    private int money;
    Example4_9()
    {  
        money=2000;
    }
    private int getMoney()
    {
       return money;
    }
    public static void main(String args[])
    {
       Example  exa=new Example();
       exa.money=3000;
       int m=exa.getMoney();
       System.out.println("money="+m);
    }
}


例子10
class Father
{  
    private int money;
    int weight=100;
    String speak(String s)
    {
      return s ;
    }
}
class Son extends Father
{  
    String hand ;
    void f()
    {
      weight=200;
      System.out.println(weight);
    }
}
class Suizi extends Son
{
    String foot ;
}
public class Example4_10
{  
    public static void main(String args[])
    {
       Son son=new Son();
       Suizi sunzi=new Suizi();
       son.hand="
两只手 ";
       sunzi.hand="
两小只手 ";
       sunzi.foot="
两只脚 ";
       System.out.println(son.hand);
       son.f();
       System.out.println(sunzi.weight+":"+sunzi.hand+":"+sunzi.foot);
       System.out.println(sunzi.speak("
我是孙子"));
    }
}    


例子11
Father.java:
package tom.jiafei;
public class  Father
{
    int  height;
    protected int money=120;
    public   int weight;
    protected int getMoney()
    {  
      return money;
    }
    void setMoney(int newMoney)
    {  
      money=newMoney;
    }
}


Jerry.java:
package sun.com;
import tom.jiafei.Father;
public class Jerry extends Father          //Jerry
Father在不同的包中.
{  
    void f()
    {
      money=1000;                          //
合法,
      //height=1.89f;                        //
非法,因为Jerry没有继承友好的height
      System.out.println(money);              //
输出结果是1000
      //setMoney(300);                      //
非法,因为Jerry没有继承友好的方法setMoney
     int number=getMoney();                //
合法.
      System.out.println(number);            //
输出结果是1000
    }
    public static void main(String args[])
    {  
       Jerry  jerry=new Jerry();
       jerry.f();
    }
}


例子
protected
的进一步说明
A.java

package tom.jiafei;
public class  A
{
    protected int x=120;
    protected void fA()
    {  
      System.out.println("
我是A类中的protected方法");
      System.out.println("x="+x);
    }
}
B.java

package sun.com;
import tom.jiafei.A;
public class B extends A
{
    protected void fB()
    {  
      System.out.println("
我是B类中自己定义的方法");
    }
    public static void main(String args[])
    {
      B b=new B(); //
对象bB类中.
      b.x=1000;  //
合法.
      b.fA();    //
合法.
      b.fB();    //
合法.
    }
}


DL.java

package sun.com;
import sun.com.B;
public class DL
{
    public static void main(String args[])
    {
       B b=new B(); //
对象bDL类中.
       b.x=1000;  //
非法,因为对象b的成员变量x是从A类继承的,DLA不在同一包中.
       b.fA();    //
非法.因为方法fAB类从A类继承的protected方法,DLA不在同一包中.
       b.fB();    //
合法,因为方法fBB类中自己定义的protected方法, DL类和B类在同一包中.
    }
}


Example.java
package tom.jiafei;
import sun.com.B;
public class Example
{
    public static void main(String args[])
    {
       B b=new B(); //
对象bExample类中.
       b.x=1000;  //
合法,因为对象b的成员变量x是从A类继承的,ExampleA 同一包中.
       b.fA(); //
合法.因为方法fAB类从A类继承的protected方法,ExampleA在同一包中.
       b.fB(); //
非法,因为方法fBB类中自己定义的protected方法, Example类和B类不在同一
             //
包中.
    }
}


例子12
import java.applet.*;
import java.awt.*;
class A
{  
    private int number=100;
    float f(int x,int y)
    {  
       return x+y;
    }
    float g(float x,float y)
    {
       return x+y+number;
    }
}
class B extends A
{
    float f(int x,int y)
    {
       return x*y;
    }  
}
public class Example
{  
    public static void main(String args[])
    {  
      B b=new B();
      System.out.println(b.f(2,5));   //
调用重写的方法。
      System.out.println(b.g(2,5));   //b
调用继承的父类的方法。
    }
}


例子13
class  
类人猿
{  
    private int n=100;
    void crySpeak(String s)
    {  
      System.out.println(s);
    }  
}
class People extends
类人猿
{
    void computer(int a,int b)
    {  
       int c=a*b;
       System.out.println(c);
    }
void crySpeak(String s)
    {
       System.out.println("**"+s+"**");
    }  
}
class Example
{  public static void main(String args[])
    {  
      
类人猿 monkey=new People();   //monkeyPeople对象的上转型对象。
       monkey.crySpeak("I love this game");
       //monkey.n=23;                //
非法,因为子类未继承n.
       //monkey.computer(12,19);     //
非法,computer是子类新增的功能.
       People people=(People)monkey; //
把上转型对象强制转化为子类的对象。
       people.computer(10,10);
    }
}


例子14
class  
动物
{  void cry()
    {
    }
}
class
extends 动物 {
{  void cry()
    {  System.out.println("
汪汪.....");
    }  
}
class
extends 动物
{  void cry()
    {  System.out.println("
喵喵.....");
    }  
}
class Example4_14
{  public static void main(String args[])
    {  
动物 dongwu;
       if(Math.random()>=0.5)    
          {
            dongwu=new
();
            dongwu.cry();
          }
       else
         {
           dongwu=new
();
            ongwu.cry();
          }
    }
}


例子15
abstract class
图形
{  
    public abstract double
求面积();
}
class
梯形 extends 图形
{
    double a,b,h;
    
梯形(double a,double b,double h)
    {  
       this.a=a;this.b=b;this.h=h;
    }
    public double
求面积()
    {  
         return((1/2.0)*(a+b)*h);
    }
}
class
圆形 extends 图形
{  
    double r;
    
圆形(double r)
    {  
       this.r=r;
    }
    public double
求面积()
    {  
       return(3.14*r*r);
    }
}
class

{  
    
图形 ;
    double
;
    
(图形 ,double )
    {
        this.
=;
        this.
=;
    }
    void
换底(图形 )
    {
        this.
=;
    }
    public double
求体积()
    {  
       return (
.求面积()*)/3.0;
    }
}
public class Example4_15
{
    public static void main(String args[])
    {
      
zui;
      
图形 tuxing;
       tuxing=new
梯形(2.0,7.0,10.7);
       System.out.println("
梯形的面积"+tuxing.求面积());
       zui=new  
(tuxing,30);
       System.out.println("
梯形底的堆的体积"+zui.求体积());
       tuxing=new
圆形(10);
       System.out.println("
半径是10的圆的面积"+tuxing.求面积());
       zui.
换底(tuxing);
       System.out.println("
圆形底的堆的体积"+zui.求体积());
    }
}


例子16
class Student
{  
    int number;String name;
    Student(int number,String name)
    {  
        this.number=number;
        this.name=name;
        System.out.println("I am "+name+ "my number is "+number);
    }
}
class Univer_Student extends Student
{  
    boolean
婚否;
    Univer_Student(int number,String name,boolean b)
    {
       super(number,name);
      
婚否=b;
       System.out.println("
婚否="+婚否);
    }
}
public class Example4_16
{
    public static void main(String args[])
    {  
      Univer_Student zhang=new Univer_Student(9901,"
和晓林",false);
    }
}


例子17
class Sum
{  
    int n;
    float f()
    {  
       float sum=0;
       for(int i=1;i<=n;i++)
           sum=sum+i;
           return sum;  
    }
}
class Average extends Sum
{  
    int n;  
    float f()
    {  
       float c;
       super.n=n;
       c=super.f();
       return c/n;
    }
    float g()
    {
       float c;
       c=super.f();
       return c/2;
    }
}
public class Example4_17
{  
    public static void main(String args[])
    {  
       Average aver=new Average();
       aver.n=100;
       float result_1=aver.f();
       float result_2=aver.g();
       System.out.println("result_1="+result_1);
       System.out.println("result_2="+result_2);
    }
}


例子18
import java.applet.*;
import java.awt.*;
interface Computable
{  
    final int MAX=100;
    void speak(String s);
    int f(int x);
    float g(float x,float y);
}
class China implements Computable
{
    int xuehao;
    public  int f(int x)   //
不要忘记public关键字。
    {
       int sum=0;
       for(int i=1;i<=x;i++)
          {
            sum=sum+i;
          }
       return sum;
    }
    public float g(float x,float y)
    {  
         return 6;                   //
至少有return语句。  
    }
    public void speak(String s)
    {
    }
}
class Japan implements Computable
{
    int xuehao;
    public int f(int x)
    {  
        return 68;
    }
    public  float g(float x,float y)
    {
        return x+y;
    }
public void speak(String s)
    {                            //
必须有方法体,但体内可以没有任何语句。
    }
}
public class Example4_18  extends Applet
{
    China Li;
    Japan Henlu;
    public void init()
    {  
       Li=new China();  
       Henlu=new Japan();  
       Li.xuehao=991898;
       Henlu.xuehao=941448;
    }
    public void paint(Graphics g)
    {
       g.drawString("xuehao:"+Li.MAX+Li.xuehao+"
1100求和"+Li.f(100),10,20);
       g.drawString("xuehao:"+Henlu.MAX+Henlu.xuehao+"
加法"+Henlu.g(2.0f,3.0f),10,40);
    }
}  


例子19
interface  
收费
{
    public void  
收取费用();
}
interface  
调节温度
{
    public void  controlTemperature();
}
class
公共汽车 implements 收费
{  
    public  void
收取费用()
    {  
       System.out.println("
公共汽车:一元/,不计算公里数");
    }
}
class
出租车 implements 收费, 调节温度
{  
    public void
收取费用()
    {  
       System.out.println("
出租车:1.60/公里,起价3公里");
    }
    public void  controlTemperature()
    {  
       System.out.println("
安装了Hair空调");
    }
}
class
电影院 implements 收费,调节温度
{  
    public void
收取费用()
    {
        System.out.println("
电影院:门票,十元/");
    }
    public void  controlTemperature()
    {  
        System.out.println("
安装了中央空调");
    }
}
class Example4_19
{
    public static void main(String args[])
    {  
      
公共汽车 七路=new 公共汽车();
      
出租车   天宇=new 出租车();
      
电影院   红星=new 电影院();
      
七路.收取费用();
      
天宇.收取费用();
      
红星.收取费用();
      
天宇.controlTemperature();
      
红星.controlTemperature();
    }
}


例子20
interface  ShowMessage
{  
    void
显示商标(String s);
}
class TV implements ShowMessage
{  
    public void
显示商标(String s)
    {
       System.out.println(s);
    }
}
class PC implements ShowMessage
{
    public void
显示商标(String s)
    {  
        System.out.println(s);
    }
}
public class Example4_20
{  
    public static void main(String args[])
    {
       ShowMessage sm;                  //
声明接口变量。
       sm=new TV();                     //
接口变量中存放对象的引用。
       sm.
显示商标("长城牌电视机");      //接口回调。
       sm=new PC();                     //
接口变量中存放对象的引用。
       sm.
显示商标("联想奔月5008PC"); //接口回调。
    }
}


例子21
interface  Computerable
{
    public  double
求面积();
}
class
梯形 implements Computerable
{
    double a,b,h;
    
梯形(double a,double b,double h)
    {  
        this.a=a;this.b=b;this.h=h;
    }
    public double
求面积()
    {  
        return((1/2.0)*(a+b)*h);
    }
}
class
圆形 implements Computerable
{  
    double r;
    
圆形(double r)
    {  
       this.r=r;
    }
    public double
求面积()
    {
       return(3.14*r*r);
    }
}
class

{
    Computerable
;           //声明一个接口变量,可以回调"求面积"方法。
    double
;
    
(Computerable ,double )
    {  
       this.
=;
       this.
=;
    }
    void
换底(Computerable )
    {  
        this.
=;
    }
     public double
求体积()
    {  
      return (
.求面积()*)/3.0;
    }
}
public class Example4_21
{  
    public static void main(String args[])
    {  
      
zui;
       Computerable bottom;
       bottom=new
梯形(2.0,7.0,10.7); //接口变量中存放对象的引用。
       System.out.println("
梯形的面积"+bottom.求面积()); //bottom接口回调,求面积。
       zui=new  
(bottom,30);
       System.out.println("
梯形底的堆的体积"+zui.求体积());
       bottom=new
圆形(10);  //接口变量中存放对象的引用。
       System.out.println("
半径是10的圆的面积"+bottom.求面积());
       zui.
换底(bottom);
       System.out.println("
圆形底的堆的体积"+zui.求体积());
    }
}


例子22
public class Example4_22
{  
    public static void main(String args[])
    {  
      int n=0,m=0,t=0;
      try
         {  
            t=9999;
            m=Integer.parseInt("8888");
            n=Integer.parseInt("12s3a");    //
发生异常,转向catch
            System.out.println("
我没有机会输出");
         }
      catch(Exception e)
         {
           System.out.println("
发生异常");
           n=123;
         }
      System.out.println("n="+n+",m="+m+",t="+t);
    }
}



例子23
class MyException extends Exception
{
    String message;
    MyException()
    {
    message="
数字不是正数";
    }
     public String toString()
    {
      return message;
    }
}
class YourException extends Exception
{
    String message;
    YourException()
    {
    message="
数字不是偶数";
    }
public String toString()
    {
      return message;
    }
}
class A
{
    public void f(int n) throws MyException,YourException
    {
      if(n<0)
        {
          throw(new  MyException());             //
抛出异常,结束方法的执行。
        }
      if(n%2!=0)
        {
          throw(new  YourException());           //
抛出异常,,结束方法的执行。
        }
      double number=Math.sqrt(n);
      System.out.println(number);
    }
public static void main(String args[])
    {
      A a=new A();
     try
         {
           a.f(9);
         }
      catch(MyException e)
         {
            System.out.println(e.toString());
         }
      catch(YourException e)
         {
            System.out.println(e.toString());
         }
       try
         {
           a.f(-8);
         }
      catch(MyException e)
         {
            System.out.println(e.toString());
         }
      catch(YourException e)
         {
            System.out.println(e.toString());
         }
       try
         {
           a.f(16);
         }
      catch(MyException e)
         {
            System.out.println(e.toString());
         }
       catch(YourException e)
         {
            System.out.println(e.toString());
         }
    }
}



常用实用类
例子1
class Example5_1
{
    public static void main(String args[])
    {
       String s1,s2;
       s1=new String("we are students");
       s2=new String("we are students");
       System.out.println(s1.equals(s2));    //
输出结果是:true
       System.out.println(s1==s2);         //
输出结果是:false
       String s3,s4;
       s3="how are you";
       s4="how are you";
       System.out.println(s3.equals(s4));    //
输出结果是:true
       System.out.println(s3==s4);         //
输出结果是:true    
    }
}


例子2
class Example5_2
{   public static void main(String args[])
    {  int number=0;
       String s="student;entropy;engage,english,client";
       for(int k=0;k<s.length();k++)
        {  if(s.regionMatches(k,"en",0,2))
             {  number++;
             }
         }
       System.out.println("number="+number);
    }
}


例子3
class Example5_3
{  public static void main(String args[])
    {  String a[]={"boy","apple","Applet","girl","Hat"};
       for(int i=0;i<a.length-1;i++)
          {for(int j=i+1;j<a.length;j++)
            {  if(a[j].compareTo(a[i])<0)
               {  String temp=a[i];
                   a[i]=a[j];
                   a[j]=temp;
                }
            }
         }
      for(int i=0;i<a.length;i++)
         {  System.out.print("  "+a[i]);
         }
    }
}

例子4
public class Example5_4
{  public static void main(String args[])
    {  double n,sum=0.0 ;
       for(int i=0;i<args.length;i++)
        {  sum=sum+Double.parseDouble(args[i]);
        }
      n=sum/args.length;
      System.out.println("
平均数:"+n);
    }
}

例子5
import java.util.Date;
import java.awt.*;
public class Example5_5
{  
    public static void main(String args[])
    {
      Date date=new Date();
      Button button=new Button("
确定");
      System.out.println(date.toString());
      System.out.println(button.toString());  
    }
}

例子6
class Example5_6
{  
    public static void main(String args[])
    {  
       char c[],d[];
       String s=”
巴西足球队击败德国足球队”;
       c=new char[2];
       s.getChars(5,7,c,0);
       System.out.println&copy;;
       d=new char[s.length()];
       s.getChars(7,12,d,0);
       s.getChars(5,7,d,5);
       s.getChars(0,5,d,7);
       System.out.println(d);
    }
}

例子7
class Example5_7
{  
    public static void main(String args[])
    {
       String s="
列车时刻表";
       char a[]=s.toCharArray();
       for(int i=0;i<a.length;i++)
         {  a[i]=(char)(a[i]^'t');
         }
       String secret=new String(a);
      System.out.println("
密文:"+secret);
      for(int i=0;i<a.length;i++)
        {  
            a[i]=(char)(a[i]^'t');
        }
    String code=new String(a);  
    System.out.println("
原文:"+code);
    }
}

例子8
public class Example5_8
{
    public static void main(String args[])
    {  
       byte d[]="
你我他".getBytes();          
       System.out.println("
数组d的长度是(一个汉字占两个字节):"+d.length);
       String s=new String(d,0,2);
       System.out.println(s);
    }
}

例子9
class Example5_9
{
    public static void main(String args[])
    {
      StringBuffer str=new StringBuffer();
       str.append("
大家好");
       System.out.println("str:"+str);
      System.out.println("length:"+str.length());
       System.out.println("capacity:"+str.capacity());
       str.append("
我们大家都很愿意学习Java语言");
       System.out.println("str:"+str);
       System.out.println("length:"+str.length());
      System.out.println("capacity:"+str.capacity());
       StringBuffer sb=new StringBuffer("Hello");
       System.out.println("length:"+sb.length());
       System.out.println("capacity:"+sb.capacity());
    }
}

例子10
class Example5_10
{
    public static void main(String args[])
    {
       StringBuffer str=new StringBuffer("
我们大家都很愿意学习Java语言");
       str.setCharAt(0 ,'w');
       str.setCharAt(1 ,'e');
       System.out.println(str);
       str.insert(2, " all");
       System.out.println(str);
       str.delete(6,8);
       System.out.println(str);
       int index=str.indexOf("
");
       str.replace(index,str.length()," love java");
       System.out.println(str);
    }
}

例子11
import java.util.*;
public class Example5_11
{  
    public static void main(String args[])
    {  
       String s="we are stud,ents";
       StringTokenizer fenxi=new StringTokenizer(s," ,"); //
空格和逗号做分
       int number=fenxi.countTokens();
       while(fenxi.hasMoreTokens())
        {
           String str=fenxi.nextToken();
           System.out.println(str);
           System.out.println("
还剩"+fenxi.countTokens()+"个单词");
        }
      System.out.println("s
共有单词:"+number+"");
    }
}

例子12
import java.util.*;
public class Example5_12
{  public static void main(String args[])
   {  String s=new String("abcABC123");
      System.out.println(s);    
      char a[]=s.toCharArray();
      for(int i=0;i<a.length;i++)
       { if(Character.isLowerCase(a[i]))
          { a[i]=Character.toUpperCase(a[i]);
          }
       else if(Character.isUpperCase(a[i]))
          { a[i]=Character.toLowerCase(a[i]);
          }
       }
     s=new String(a);
     System.out.println(s);      
   }
}

例子13
import java.util.Date;
import java.text.SimpleDateFormat;
class Example5_13
{  
    public static void main(String args[])
    {
      Date nowTime=new Date();
      System.out.println("
现在的时间:"+nowTime);
      SimpleDateFormat matter1=new SimpleDateFormat("yyyy
MMdd 北京时间");
      System.out.println("
现在的时间:"+matter1.format(nowTime));
      SimpleDateFormat matter2=
      new SimpleDateFormat("yyyy
MMEddHHmmss 北京时间");
      System.out.println("
现在的时间:"+matter2.format(nowTime));
      SimpleDateFormat matter3=
      new SimpleDateFormat("
北京时间ddHHMMM ssmmEE");
      System.out.println("
现在的时间:"+matter3.format(nowTime));
      long time=-1800;
      Date date=new Date(time);
      System.out.println("-1800
秒表示的日期时间是:"+date);
    }
}

例子14
import java.util.*;
class Example5_14
{
    public static void main(String args[])
   {  
      Calendar calendar=Calendar.getInstance(); //
创建一个日历对象。
      calendar.setTime(new Date());          //
用当前时间初始化日历时间。
      String
=String.valueOf(calendar.get(Calendar.YEAR)),
            
=String.valueOf(calendar.get(Calendar.MONTH)+1),
            
=String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)),
            
星期=String.valueOf(calendar.get(Calendar.DAY_OF_WEEK)-1);
      int hour=calendar.get(Calendar.HOUR_OF_DAY),
          minute=calendar.get(Calendar.MINUTE),
          second=calendar.get(Calendar.SECOND);
      System.out.println("
现在的时间是:");
      System.out.println(""+
+""++""++" "+ "星期"+星期);
      System.out.println(""+hour+"
"+minute+""+second+"");
      calendar.set(1962,5,29);  //
将日历翻到1962629,注意5表示六月。
      long time1962=calendar.getTimeInMillis();
      calendar.set(2003,9,5);  //
将日历翻到20031059表示十月。
      long time2003=calendar.getTimeInMillis();
      long
相隔天数=(time2003-time1962)/(1000*60*60*24);
      System.out.println("20031051962629相隔"+
相隔天数+"");
   }  
}

例子 15
import java.util.*;
class Example5_15
{
    public static void main(String args[])
{
   System.out.println("
");
       Calendar
日历=Calendar.getInstance();        
      
日历.set(2004,9,1);  //将日历翻到2004101,注意0表示一月。
       //
获取1日是星期几(get方法返回的值是1表示星期日,星期六返回的值是7):
       int
星期几=日历.get(Calendar.DAY_OF_WEEK)-1;
       String a[]=new String[
星期几+31];             //存放号码的一维数组
       for(int i=0;i<
星期几;i++)
             {
                a[i]="**";
             }
       for(int i=
星期几,n=1;i<星期几+31;i++)
             {
               if(n<=9)
                  a[i]=String.valueOf(n)+" ";
               else
                  a[i]=String.valueOf(n) ;
               n++;
             }  
      //
打印数组:
      for(int i=0;i<a.length;i++)
       {
          if(i%7==0)
          {
             System.out.println("");      //
换行。
          }
         System.out.print(" "+a[i]);
      }
   }
}

例子 16
import java.text.NumberFormat;
class Example5_16
{
    public static void main(String args[])
    {  
      double a=Math.sqrt(5);
      System.out.println("
格式化前:"+a);
      NumberFormat f=NumberFormat.getInstance();
      f.setMaximumFractionDigits(5);
      f.setMinimumIntegerDigits(3);
      String s=f.format(a);
      System.out.println("
格式化后:"+s);
      System.out.println("
得到的随机数:");
      int number=8;
      for(int i=1;i<=20;i++)
       {
         int randomNumber=(int)(Math.random()*number)+1;//
产生18之间的随机数。
         System.out.print(" "+randomNumber);
         if(i%10==0)
             System.out.println("");
       }
    }
}

例子17
import java.util.*;
class Example5_17
{
    public static void main(String args[])
    {
      Vector vector=new Vector();
      for(int i=1;i<=18;i++)
      {
        vector.add(new Integer(i));       //
向量填加18个整数对象.
      }
      int a[]=new int[vector.size()];
      int i=0;
      while(vector.size()>0)              
      {  
        int number=(int)(Math.random()*vector.size());  
        Integer integer=(Integer)vector.elementAt(number);
        a[i]=integer.intValue();                    //
得到整数对象中的int.
        vector.removeElementAt(number);            //
向量移掉number处的整数对象.
        i++;
       }
      for(i=0;i<18;i++)
      {
         System.out.print(" "+a[i]);
       }
    }
}

例子18
import java.util.*;
public class Example5_18
{
    public  static void main(String args[])
    {
      LinkedList mylist=new LinkedList();
      mylist.add("is");
      mylist.add("a");
      int number=mylist.size();
      System.out.println("
现在链表中有"+number+"个节点:");
      for(int i=0;i<number;i++)
        {
           String temp=(String)mylist.get(i);
           System.out.println("
"+i+"节点中的数据:"+temp);
        }
     mylist.addFirst("It");
     mylist.addLast("door");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值