第二章 Java-C++(上)
---类和对象
很多java初学者都有c++的基础,但对java的博大精深还有所听闻,所以笔者专门分出一章叫java-c++(类和对象),c++的读者会 觉得非常轻松,大部分的知识都在c++中学过。这样会在刚接触java时, 有一种自然的亲近感。这样java初学者就可以轻松入门。
2.object和Class翻译的问题
【新手可忽略不影响继续学习】1)object直译就是"东西,物体,对象"的意思。你
觉得一个一个窗口是一个一个东西吗?照我的意思,object就应该翻译成"东西",但是好像又上不了大雅之堂,成不了书面用语,所以我当年的师长们,就
把它翻译成对象了,我怕一些小兵嘎子们还是不明白,就直截了当告诉你object就是东西,至于这三个词儿东西,物体和对象,哪个你能懂,你就用哪个!@
马克-to-win记得师长们常说那句话,万事万物皆对象,完全可以变成,万事万物皆东西,你觉得有点道理吗?
2)class比较简单,就翻译成"类",就可以了。
3.历史上讲,对象有什么重要的? (视频下载) (全部书籍)
4.object和Class配合工作原理 (视频下载) (全部书籍)
result is:
The initial date is:0/0
After setting, the date is:2009/7
The initial date1 is:0/0
作业:做一个类叫两个数。类里有两个属性,x和y,类里有一个方法叫设置x,它可以设置x的大小。类里还有一个方法,是打印xy。可以把xy两个值都打印出来。提高部分:类里还有一个方法叫做增加x。这个方法可以把x和输入参数相加返回。做测试类测试。
Assignment(作业): make a class called Window which has two properties called x,y and a method called drag(dx,dy), the method of drag can change the coordination of x,y, x=x+dx; also you need to create another method called print(), which can print the current x,y coordination. In your main method, you create two objects window1,window2, then you can drag window1 or window2, then print their x,y coordination.百度翻译:做一个类叫window,他有两个属性叫x,y,1个方法,叫做拖拽drag , 方法拖拽能够改变x,y的坐标,也需要创建另外一个方法叫做print, 它能够打印当前的x,y坐标,在你的主函数当中,你创建两个对象, window1,window2,然后你能拖拽window1,window2,然后打印他们的坐标。
Assignment2(作业): make a class of SpriteHero which has two properties called x,y,experience, and a method called move(dx,dy) and hit(), print method can print out all of the properties. when hit, then experience is increased by 1. then make main to test.( initially experience value is 5. x, y is 30,30) 百度翻译:做一个类叫做精灵英雄,他有两个属性叫x,y和经验值和三个方法叫做移动,点击,打印方法,能够打印出所有的属性, 当点击的时候,经验值就被增加一, 然后做一个主函数测试,它们经验值是5。x,y是30,30。
实验
本章源码
class HelloClass {
int i;
int getI() {
return i;
}
void setI(int ii) {
i = ii;
}
}
public class Test {
public static void main(String[] args) {
HelloClass hc = new HelloClass();
hc.setI(9);
int ri = hc.getI();
System.out.println(ri);
}
}
result is: 9
第二节 类和对象的相关知识
1.构造方法(Constructor):
1.1 用new关键字创建一个对象的时候,构造方法被java虚拟机正常调用
package com;
class FourAng {
double w;
double h;
FourAng() {
w = 2.0;
h = 2.0;
}
FourAng(double x, double y) {
w = x;
h = y;
}
double area() {
return w*h;
}
}
public class Test {
public static void main(String[] args) {
FourAng c = new FourAng();//正常调用无参构造函数。
FourAng d = new FourAng(3, 10);//正常调用2个参数的构造函数。
System.out.println(c.area());
System.out.println(d.area());
}
}
result is:
4.0
30.0
作业: a班的门关了,b班的门开了又关了。The name of method(方法) should be closeDoor(), openDoor(), the property(属性) of the class is door.
1.2 当没有任何构造函数,java编译器,会插入一个默认的构造函数 (视频下载) (全部书籍)
见下面的例子:
class Line {
double x = 0.02;
double y;
}
public class Test {
public static void main(String[] args) {
Line c = new Line();
System.out.println(c.x);
System.out.println(c.y);
}
}
结果:
0.02
0.0
class Circle1 {
double x = 0.02;
double y;
public Circle1(){
}
}
public class Test {
public static void main(String[] args) {
Circle1 c = new Circle1();
System.out.println(c.x);
System.out.println(c.y);
}
}
结果:
0.02
0.0
解释一下上面的例子@马克-to-win:实验表明:最开始x=0,且y=0,后来执行构造函数之前,系统先用double x=0.02; double y=0;赋值, 之后再用构造函数的方法最后赋值。如构造函数中什么都没做就用系统开始的赋值。
类其中的变量为final时的用法: (视频下载) (全部书籍)
类当中final变量没有初始缺省值,必须在构造函数中赋值或直接当时赋值。否则报错。
public class Test {
final int i;
Test(){
i=3;
}
public static void main(final String[] args) {
Test t=new Test();
System.out.println("i = " + t.i);
}
}
结果:
i = 3
2.重载(OverLoad):(参见第一章的7.3方法重载)
Java支持方法名重载,使得多个方法可以共享一个名字。
重载的方法参数必须有所区别,即
参数的类型不同,或
参数的顺序不同,或
参数的个数不同。( 马克-to-win: 当我试图写带着同样的输入参数,不同的返回值的两个方法时,系统直接报错。所以重载只和输入参数有关系。 when I try to write two method with same
arguments ,but different return value. it directly report error. So overload
only has something to do with arguments.)
当一个重载的方法被调用时,Java在调用方法的参数和方法的自变量之间寻找匹配。 (视频下载) (全部书籍)
但是,这种匹配并不总是精确的。只有在找不到精确匹配时,Java的自动转换才会起作用。 (如果定义了test(int),当然先调用test(int)而不会调用test(double)。 )
//自动类型转换 Automatic type conversions() apply to overloading.
class Overl {
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
public class Test {
public static void main(String args[]) {
Overl ob = new Overl();
int i = 80;
ob.test(i); // 没有int类型,所以调用double类型的自动转换。this will invoke test(double)
ob.test(555.5); // 准确调用,this will invoke test(double)
ob.test(5, 8);//准确调用
}
}
result结果 is:
Inside test(double) a: 80.0
Inside test(double) a: 555.5
a and b: 5 8
Assignment: practice overload, make two methods,add(int a,int b), add(int a,int b,int c)
3.一个对象可能有多个参考(One Object can
have many Reference)
result is:
p1: 10
p2: 10
p3: 0
4.this关键字(this key word) (视频下载) (全部书籍)
继上一小节,(3.一个对象可能有多个参考)this是当中的一个参考!指向他自己。
class MyTestDate {
int year;
int month;
MyTestDate(int year, int month, int day) {
/*为了学习this的用法,本例中,我们故意用了两个相同的year,一个是全类作用范围的(整个类中都有效马克-to-win):int year; 另外一个是,只有本块儿才起作用的块作用范围的MyTestDate(int year, 这两个year不是一个year,如果把this.year = year; 变成 year = year,这两个year都成了块作用范围的那个year, 这样全类作用范围的那个year等于没赋值,还是0,输出结果就会变成0/0/0, if here you use year = year;month = month; result is 0/0/0, because this.year still is 0.local variable 's scope is less than the "this" variable's scope.
*/
this.year = year;//this.year指前面类范围的变量 int year。
this.month = month;
}
void setYear(int year) {
this.year = year;
}
void setMonth(int month) {
this.month = month;
}
/*系统见到System.out.println,会自动调用toString,初学者没必要深究*/
public String toString() {
return "" + year + "/" + month ;
}
}
public class Test {
public static void main(String[] args) {
MyTestDate date = new MyTestDate(2009, 7, 18);
System.out.println(date);
date.setYear(2009);
date.setMonth(5);
System.out.println(date);
MyTestDate date1 = new MyTestDate(2009, 1, 1);
System.out.println(date1);
date1.setYear(2006);
date1.setMonth(6);
System.out.println(date1);
}
}
result is:
2009/7
【新手可忽略不影响继续学习】(视频下载) (全部书籍) 下面例子中setYear中的return this;返回了一个指向对象的指针,this.setMonth(8).setDay(20);是合法的,如果像原来的例子一样什么都不返回,就成了void.setMonth(8).setDay(20); 马克-to-win,系统就该报错了
class MyTestDate {类变量和实例变量的区别
相对于static(静态的)或说类的, 本章开始提到的都是instance(实例的)或说对象的。 每个对象都有自己的一份儿对象域或实例域,相互之间没关系, 不共享。 我们可以从对象中访问实例变量。
类变量或说静态变量跟实例变量是不一样的,(视频下载) (全部书籍)不管创建了多少个对象,系统只为每个类变量分配一次存储空间。系统为类变量分配的内存是在执行main方法时马克-to-win, 就是在程序最最开始的时候(见下面StaticDemo的例子)。所有的对象共享了类变量。可以通过对象或者通过类本身来访问类变量。
静态方法(方法前冠以static)和实例方法(前面未冠以static)的区别 (视频下载) (全部书籍)
调用静态方法或说类方法时,可以使用类名做前缀,也可以使用某一个具体的对象名;通常使用类名。
static方法只能处理static域或静态方法。实例方法可以访问实例域, 静态域或静态方法, 记住都行。
result is:
开始观察StaticTest.a和Test.c
a = 4马克-to-win43
a = 4马克-to-win43
a = 4马克-to-win43
a = 4实例马克-to-win43
b = 5
assignment: make a method which can print "hello world!".
result is:
0
Static块:该类的任何方法被首次触碰到时(马克-to-win: when you touch Test的main方法时),Static块被运行。可以在里面初始化你的static变量,不能访问实例变量。在所有静态变量初始化之后运行,见例子。
class Test1{
static {
System.out.println("Static block Test1 initialized.");
}
}
public class Test {
/*下面两句话是在静态块儿之前执行,所以它的值,被静态块儿里面赋的值所覆盖掉。马克-to-win, the following two statements are before the execution of the static block.*/
static int a = 3;
static int b;
int c;
static void cal(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
// 静态块儿Static block
static {
// c=9; 是错误的,will cause an error.
System.out.println("Static block initialized.");
a = 9;
b = a * 4;
System.out.println("a = " + a);
System.out.println("b = " + b); }
public static void main(String args[]) {
System.out.println("in main");
/* main and cal 都是静态块儿,所以可以这样调用,here main and cal is on the same class and same level, so can use in this way.*/
cal(42);
new Test1();
}
}
结果:
Static block initialized.
a = 9
b = 36
in main
x = 42
a = 9
b = 36
Static block Test1 initialized.
Assignment: 3) bawei, static block {registration, pay tuition,} normal program
is "start studying."
class Student {
int age;
String name;
static int count;
public Student() {
System.out.println("in constructor");
}
/*只执行一次。*/
static {
System.out.println("hello");
count = 0;
}
}
public class Test {
public static void main(String[] args) {
Student s = new Student();
Student s1 = new Student();
}
}
result is :
hello
in constructor
in constructor
assignment: class: School has a static member called count which records how many schools we have. count's initial value is 0, count increments in School's constructor.
assignment2: car( mercedes, BMW, static member count is increased in the constructor.)
assignement: 1) class Car(name,price, static TotalSum), static block initialize TotalSum=0; whenever you buy a car, constructor add money to the TotalSum. finally, print out the TotalSum.
2) make a MyMath class which has absolute and power,add(int, int), add(int, int, int)
7.对象的属性可以是另外一个对象或对象的参考 (视频下载) (全部书籍)
通过这种方法可以迅速构建一个比较大的系统。
class Motor {
Light[] lights;
Handle left, right;
KickStart ks;
Motor() {
lights = new Light[2];
lights[0] = new Light();
lights[1] = new Light();
left = new Handle();
right = new Handle();
ks=new KickStart();
}
}
class Handle {
Grip grip;//grip中文是把套的意思
Handle() {
grip = new Grip();
}
void turnLeft() {
System.out.println("左转车把....");
}
}
class Light {
void turnon() {
System.out.println("开灯.....");
}
}
class KickStart {
void kick() {
System.out.println("踹一脚,启动.........");
}
}
class Grip {
void rollup() {
System.out.println("往上转一下把套,发动.........");
}
}
public class Test {
public static void main(String[] args) {
Motor myMotor = new Motor();
System.out.println("夜间启动摩托车的步骤");
for(int i=0;i<2;i++) myMotor.lights[i].turnon();
myMotor.left.grip.rollup();
myMotor.ks.kick();
}
}
result is:
夜间启动摩托车的步骤
开灯.....
开灯.....
往上转一下把套,发动.........
踹一脚,启动.........
class Photoshop {
/* 通过调试发现写成 static Photoshop photoshop或static Photoshop
photoshop=null;是一样的,开始时都为null,马克-to-win,另外在调试时 可以写上观察Photoshop.photoshop的值,它是独立于任何对象之外的,从程序开始运行的main方法时, 这个值就有了, 只不过为null罢了,
*/
static Photoshop photoshop;//这个值独立于任何对象存在,实例化任何对象之前,这个成员就有可能有值。
static Photoshop getInstanceQixy() {
if (photoshop == null) {
photoshop = new Photoshop();
System.out.println("成功创建");
} else {
System.out.println("已经创建了该类的实例,不能再创建!");
}
return photoshop;
}
void drawImage() {
System.out.println("draw image using photoshop");
}
}
public class Test {
public static void main(String[] args) {
Photoshop photoshopI1 = Photoshop.getInstanceQixy();
Photoshop photoshopI2 = Photoshop.getInstanceQixy();
System.out.println(photoshopI1 == photoshopI2);
System.out.println(photoshopI1 == Photoshop.photoshop); photoshopI1.drawImage();
Photoshop photoshopI3 = new Photoshop();
System.out.println(photoshopI1 == photoshopI3);
}
}
result is:
成功创建
已经创建了该类的实例,不能再创建!
true
true
draw image using photoshop
false
反思一下: 如果写成:static Photoshop photoshop=new Photoshop();程序执行到main时,实例化就被执行了,而现在会在Photoshop.getInstanceQixy();时才对象实例化。执行的时机不一样。有时可能不用初始化的这么早。
class Photoshop {
static Photoshop photoshop=new Photoshop();
static Photoshop getInstanceQixy() {
return photoshop;
}
void drawImage() {
System.out.println("draw image using photoshop");
}
}
public class Test {
public static void main(String[] args) {
Photoshop photoshopI1 = Photoshop.getInstanceQixy();
Photoshop photoshopI2 = Photoshop.getInstanceQixy();
System.out.println(photoshopI1 == photoshopI2);
photoshopI1.drawImage();
Photoshop photoshopI3 = new Photoshop();
System.out.println(photoshopI1 == photoshopI3);
}
}
Assignment: make a photoshop instance using Singleton, call its method of drawImage(), additional requiredment:after the first time to activate the photoshop, from the second time on, when you activate it, it will print "you have already activate one photoshop."
Java的访问指示符分类1.public(公共的,全局的)2.private(私有的,局部的)3.protected(受保护的)4.默认访问级别。
public:public成员可以被你的程序中的任何其他代码访问。
private :private成员只能被它的类中的其他成员访问。
默认访问级别:如果不使用访问指示符,该类成员为默认访问。即在它自己的包内为public,但在它的包以外不能被存取。
封装encapsulate的概念:就是把一部分属性和方法非公有化,从而控制谁可以访问他们。 (视频下载) (全部书籍)
class Test3 {
int a; // default access访问
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}
public class Test {
public static void main(String args[]) {
Test3 ob = new Test3();
// These are OK,a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error,错误
//ob.c = 100; // Error!, 因为c是私有变量
//你必须通过方法才能访问到c, You must access c through its methods
ob.setc(100); // OK
System.out.println("a,b,and c: " + ob.a + " " + ob.b + " " + ob.getc());
}
}
输出结果:
a,b,and c: 10 20 100
为了区分开public和缺省的区别,我们要引进包(package)的概念。包就像咱们磁盘上的目录一样,马克-to-win。package a;就是定义说当前的目录为a。底下编的任何的类,都会出现在当前的这个目录a里。import b;就是导入b目录当中的类资源,因为我们在运行当前目录当中的类时,需要b目录当中的类资源。导入之后,b目录当中的类随便用。(视频下载) (全部书籍)
eclipse当中如何添加包?在new class时,其中有个项, 在其中写上你的包名就可以了。注意再做底下的实验时,要分别new两个类,这样系统会产生两个文件。
package p1;
public class P1Test3 {//前面必须得加个public,否则从别的包里没法访问到这个类
int a; // default access
public int b; // public access
private int c; // private access
//前面必须得加个public,否则从别的包里没法用这个方法,马克-to-win
public void setc(int i) { // set c's value
c = i;
}
public int getc() { // get c's value
return c;
}
}
package p2;
import p1.P1Test3;
public class Test {
public static void main(String args[]) {
P1Test3 ob = new P1Test3();
// ob.a = 10;//这样写错误,这里的a必须在P1Test3类中换成public权限才可以工作, 因为是在不同的包里
ob.b = 20;
// ob.c = 100; // 错误Error!, c是私有的
ob.setc(100); // OK
System.out.println("b,and c: " + " " + ob.b + " " + ob.getc());
}
}
输出结果:
b,and c: 20 100
assignment: a class Test has a private member called c, if you don't have a c's setter, can you modify its value except constructor? (answer: no) How can you change the value of c?(answer: add a setter)
第三节 java的常用类
String类很常用,很重要。
String不像int或float, 它是参考类型。final类型, 不能被继承,String is a Reference Type,Defined in java.lang package
常用方法:
length()
String greeting = “Hello”;
int n = greeting.length();//is 5
charAt(n)(取某个位置字符)
char first = greeting.charAt(0);
char last = greeting.charAt(4);
substring()(取子字符串)
String s = greeting.substring(0,3);//from 0 inclusive to 3 exclusive
Concatenation(链接)
String a = greeting + “ world!”+ 2009;
Equality(don’t use ==)(测试是否相等)
String s = “Hello”; s.equals(greeting);
“Hello”.equalsIgnoreCase(“hello”);(忽略大小写的测试相等)
result is:
'c'在第2个
'a'在第12个
'$'在第-1个
def在第3个
'c'在第14个
ijkl
def
public class Test {
public static void main(String args[]) {
String s, s1;
char charArray[] = new char[8];
s1 = new String("Hello World!");
// s1 = "Hello World!";
// 输出String的长度
System.out.println(s1.length());
s1=s1.replace("World", "mark-to-win");
System.out.println("s1 is "+s1);
// 使用charAt()翻转字符串
s = "";
for (int i = s1.length() - 1; i >= 0; i--)
s = s + s1.charAt(i);
System.out.println(s);
}
}
result is:
12
s1 is Hello mark-to-win!
!niw-ot-kram olleH
【新手可忽略不影响继续学习】(视频下载) (全部书籍)看过上面例子的童鞋一定会觉得很奇怪,s = s + s1.charAt(i); 马克-to-win, s不是老在变化吗?其实s = "";时,虚拟机会创建一个String对象,s = s + s1.charAt(i); 时,会创建一个新对象,而不是之前的s了,会导致新对象的生成,这样做次数少还没有太大的问题,如果次数多的话,很浪费空间。StringBuffer是在同一个实例上做这些事,不用生成新对象。当做的次数多的话,会节省大量空间。
Java中内存分成两种:一种是栈stack,一种是堆heap。
函数中的一些基本类型的变量(int, float)和对象的引用变量(reference)都在函数的栈中,如int a = 5,有个地方先存5,之后再让a指向那个地方。w=new Window(),是w指向Window的首地址。马克-to-win,存取速度快,稍逊于寄存器, 比堆快,
函数执行完后,Java会自动释放掉为函数里变量开辟的栈内存空间,该内存空间可以立即被另作他用。
堆heap内存用来存放由new创建的对象和数组。堆内存,负责运行时(runtime, 执行生成的class文件时)数据,由JVM的自动管理。缺点是,存取速度较慢。
栈中的引用变量指向堆中的对象或数组。
栈中有共享池的概念,(视频下载) (全部书籍)比如下面例子中,sz="hello";在栈中创建一个String对象引用变量sz,然后看看栈中有没有"hello",如果没有,则将"hello"存放进栈,并令sz指向”hello”,如果已经有”hello” 则直接令sz指向“hello”。对于int, float 类型的变量也是一样的有这种共享池的概念,
对于下面程序中:ss0 = new String( "hello" );是用new()来新建对象的,(视频下载) (全部书籍)存于堆中。每调用一次就会创建一个新的对象。当然从节省空间的角度来讲,肯定不如str="hello",有童鞋一定问,那要它有什么用?当时设计编译器时,为什么要设计它?马克-to-win,那我请问你,如果在你编程序时,你还不知道字符串内容怎么办?这时就用到new String(String original),所以,什么都有什么的用处。
(注意不能看调试窗口里value id,eclipse的问题)
public class Test
result is:
true
false
true
true
false
String class contains a static method, valueOf(). With it, you can create a String object from a value of any of the basic types
String pi = String.valueOf(3.14159);
String对象的运算符:“+”。用来连接两个字符串。
一件需要注意的事:
你不能写如下一段程序,系统会崩溃的,马克-to-win,因为他和lang包当中的类名String冲突,所以不要用lang包当中的类名当类名。因为lang包是核心包。you can not write a program like the following, the system will collapse. because it will collide with the class with the package of java.lang, so remember that don't try to use the name of class of java.lang package.
你可以用其他包当中的类名当类名写程序。比如io包当中File类。you can rewrite a class named File because it is java.io package.
class String{
String(int a)
{
System.out.println("a is"+a);
}
}
public class Test {
public static void main(String[] args) {
String d=new String(8);
}
}
输出结果:
java.lang.NoSuchMethodError: main
Exception in thread "main"
StringBuffer:String类同等的类,它允许字符串改变(原因见上一段所说)。(视频下载) (全部书籍) Overall, this avoids creating many temporary (临时)strings, in other words, without StringBuffer, you must create many temporary strings. StringBuffer的内部实现原理:马克-to-win,Every string buffer(缓存) has a capacity(容量). As long as the length of the character sequence contained in the string buffer does not exceed(超过) the capacity, it is not necessary to allocate(分配) a new internal buffer array. If the internal buffer overflows(满后溢出), it is automatically made larger.附带一句:从JDK5开始引入StringBuilder类,它是简易的StringBuffer,速度更快,但线程不安全
public class Test {
public static void main(String[] args) {
StringBuffer buffer;
buffer = new StringBuffer();
buffer.append("1");
System.out.println(buffer);
buffer.append("2");
System.out.println(buffer);
}
}
result is:
1
12
assignment: make a class called MyStringBuffer(char[] buf, initial size is 5, increment is 3, test program is you repeatedly store ordinary String,(the series is "abc","def","hlj") observe the effect.
Arrays defined in java.util package
It gives a lots of static methods to manipulate(操纵) array.
int[] result = new int[k];
Arrays.sort(result);
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] result = { 4, 5, 2, 7, 8 };
Arrays.sort(result);//当我们用到jdk自带的sort方法时,一下就排好序了,记得第一章,我们自己排序时,有多麻烦吗?
for (int i = 0; i < result.length; i++) {
System.out.println("" + result[i]);
}
}
}
result is:
2
4
5
7
8
题目1: 设置准确的时间(jdk1.1以后Date的setHours不被推荐了,所以要用Calendar设置时间)(视频下载) (全部书籍)
import java.util.*;import java.util.*;
import java.text.SimpleDateFormat;
public class Test {
public static void main(String[] args) {
Date date = new Date();//获取当前日期
SimpleDateFormat df = new SimpleDateFormat("yyyy-MMM-dd kk:mm:ss a");
System.out.println(df.format(date));//按yyyy-MMM-dd kk:mm:ss a这个格式来格式化date
SimpleDateFormat df1 = new SimpleDateFormat(
"yyyyy.MMMMM.dd GGG hh:mm aaa");
System.out.println(df1.format(date));//按yyyyy.MMMMM.dd GGG hh:mm aaa这个格式来格式化date,格式参见下表
}
}
result is:
2014-五月-29 11:34:14 上午
02014.五月.29 公元 11:34 上午
后记:有关yyyy-MMM-dd kk:mm:ss a是什么意思,可以参考SimpleDateFormat的api文档:k: Hour in day (1-24)
Letter | Date or Time Component | Presentation | Examples |
---|---|---|---|
G
| Era designator | Text | AD
|
y
| Year | Year | 1996 ; 96
|
M
| Month in year | Month | July ; Jul ; 07
|
w
| Week in year | Number | 27
|
W
| Week in month | Number | 2
|
D
| Day in year | Number | 189
|
d
| Day in month | Number | 10
|
F
| Day of week in month | Number | 2
|
E
| Day in week | Text | Tuesday ; Tue
|
a
| Am/pm marker | Text | PM
|
H
| Hour in day (0-23) | Number | 0
|
k
| Hour in day (1-24) | Number | 24
|
K
| Hour in am/pm (0-11) | Number | 0
|
h
| Hour in am/pm (1-12) | Number | 12
|
m
| Minute in hour | Number | 30
|
s
| Second in minute | Number | 55
|
S
| Millisecond | Number | 978
|
z
| Time zone | General time zone | Pacific Standard Time ; PST ; GMT-08:00
|
Z
| Time zone | RFC 822 time zone | -0800 |
题目3.1: 把一个字符串转成日期对象 (视频下载) (全部书籍)
import java.util.*;
public class Test {
public static void main(String[] args) {
Date date;
Calendar time=Calendar.getInstance();
// time.clear();
/*先把时间定位在2008年2月*/
time.set(Calendar.YEAR,2008);
time.set(Calendar.MONTH,1);//2月对应数字1,
/* int getActualMaximum(int field) Return the maximum value that this field could have, given the
current date. 下句话是按月来讲的最大天数而不是按年来讲的最大天数,那不是29吗? */
int day=time.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("day is"+day);
/* 下句话是按年来讲的最大天数而不是按月来讲的天数,那不是366吗? */
day=time.getActualMaximum(Calendar.DAY_OF_YEAR);
System.out.println("day1 is"+day);
}
}
结果是:
day is29
day1 is366
题目7: 2008年1月8日是那年中的第几星期?(视频下载) (全部书籍)
import java.util.*;
public class Test {
public static void main(String[] args) {
Date date;
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR, 2008);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 8);
System.out.println("date is"+cal.getTime());
int weekno=cal.get(Calendar.WEEK_OF_YEAR);//Calendar.WEEK_OF_YEAR是一年中第几个星期?
System.out.println("weekno is"+weekno);
}
}
结果是:
date isTue Jan 08 08:13:44 CST 2008
weekno is2
import java.util.*;
public class Test {
public static void main(String[] args) {
Date date;
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR, 2008);
cal.set(Calendar.WEEK_OF_YEAR, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("first week Monday is "+cal.getTime());
}
}
结果是:
first week Monday is Mon Dec 31 08:31:24 CST 2007
import java.util.*;
public class Test {
public static void main(String[] args) {
Date date;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2008);
cal.set(Calendar.MONTH, 4);
cal.set(Calendar.DAY_OF_MONTH, 31);
date = cal.getTime();
/* getTime()返回,从January 1, 1970, 00:00:00这个时候,到现在的毫秒数,
public long getTime() Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
,60l表明是长整型, 如果用60的话就是int类型,马克-to-win 会溢出的。 这样we must use 60l*60l*24l*30l*1000l, while we can not use 60*60*24*30*1000, otherwise it will overflow(溢出).
*/
long myTime = date.getTime() - 60l * 60l * 24l * 30l * 1000l;
/* public void setTime(long time)Sets this Date object to represent a
point in time that is time milliseconds after January 1, 1970
00:00:00 GMT. */
date.setTime(myTime);
System.out.println("mDate is" + date);
}
}
结果是:
mDate isThu May 01 13:06:11 CST 2008
题目10: 2008年8月27日和2008-08-24相差多少天?(视频下载) (全部书籍)
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class Test {
public static void main(String[] args) {
Date date = null;
Calendar cal = Calendar.getInstance();
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
try {
date = myFormatter.parse("2008-08-27");
} catch (ParseException e) {
e.printStackTrace();
}
Date mydate = null;
try {
mydate = myFormatter.parse("2008-08-24");
} catch (ParseException e) {
e.printStackTrace();
}
long dayl = (date.getTime() - mydate.getTime())
/ (24l * 60l * 60l * 1000l);
System.out.println("天数是 is " + dayl);
}
}
结果是:
天数是 is 3
Assignment:
make a class of MyArrays which implements the same function as Arrays, which
also has a method called sort which is exactly the same as the current sort.
Assignment:
1) there is a Point class inside a Circle class, you can use the following code to test.
public class CircleTest{
c.setPoint(10,10);
System.out.println(c);
System.out.println(c.area());
c.getPoint().setX(30);
c.getPoint().setY(30);
System.out.println(c);
System.out.println(c.area());
}
}
hint:
public class Circle{
private Point p;
private double r;
......
public class Point{
private int x,y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
.........
1.5)we have a Hero(x,y,height,width),two
Monsters(x,y,height,width), when hero hit a monster, hero's hp is increased by
50,monster's hp is decreased by 40, if monster's hp is less than 0, monster die.
monster will be converted to device,['1','2','3','4','5'], initially hero has 12
device slots.['0','0','0','0',.....], after hero kill a monster, the device
monster is converted to will be stored into hero's some empty device slot. if monster hit the hero, hero's hp is decreased by 40. hint: when hit, we
need to see whether
two objects collide or not. in main(), we set the initial positions for hero and
monsters.then we ask three objects to move around.then we ask them to hit
each other, finally we print out their hp.
2) sort a String such as "I am a teacher and work in school" according to the order of word,hint use StringTokenizer, Arrays, (see the above lecture)
3) use class to redo all of the assignments in Chapter1.