2009年2月6日 星期五

第35題

Given:

10. public class Hello{
11. String title;
12. int value;
13. public Hello(){
14. title += " World";
15. }
16. public Hello(int value){
17. this.value = value;
18. title = "Hello";
19. Hello();
20. }
21.
}
and:
30. Hello c = new Hello(5);
31. System.out.print(c.title);
What is the result?
A. Hello
B. Hello World
C. Compilation fails.
D. Hello World 5
E. The code runs with no output.
F. An exception is thrown at runtime.

答案:C
參考:6-5 繼承

----------------------------------------
Ans:

line 19. no such method, The method Hello() is undefined for the type Hello

第34題

Which four statements are true? (Choose four.
)


A. Has-a relationships should never be encapsulated.
B. Has-a relationships should be implemented using inheritance.
C. Has-a relationships can be implemented using instance variables.
D. Is-a relationships can be implemented using the extends keyword.
E. Is-a relationships can be implemented using the implements keyword.
F. The relationship between Movie and Actress is an example of an is-a relationship.
G. An array or a collection can be used to implement a one-to-many has-a relationship.

答案:CDEG
參考:6-5 繼承
-------------------------------------------

Ans:
A: Has-a 跟封裝沒有關係
B: Has-a 不是繼承的關係
F: Movie and Actress 是 Has-a 的關係

第33題

Given:

2. public class Hi{
3. void m1(){}
4. protected void m2(){}
5. }
6. class Lois extends Hi{
7. //insert code here
8. }
Which four code fragments, inserted independently at line 7, will compile? (Choose four.)
A. public void m1(){}
B. protected void m1(){}
C. private void m1(){}
D. void m2(){}
E. pubic void m2(){}
F. protected void m2(){}
G. private void m2(){}
答案:ABEF
參考:6-5 繼承

----------------------------------------------------
Ans:

權限(可見度)

第32題

Given:

1. class Mammal{}
2.
3. class Raccoon extends Mammal
4. Mammal m = new Mammal();
5. }
6.
7. class BabyRaccoon extends Mammal{}
Which four statments are true? (Choose four.)
A. Raccoon is-a Mammal.
B. Raccoon has-a Mammal.
C. BabyRaccoon is-a Mammal.
D. BabyRaccoon is-a Raccoon.
E. BabyRaccoon has-a Mammal.
F. BabyRaccoon is-a BabyRaccoon.
答案:ABCF
參考:6-5 繼承

-----------------------------------------------------
ANS:

A. Raccoon is-a Mammal. //Raccoon 繼承了 Mammal

B. Raccoon has-a Mammal. //Raccoon 有Mammal的屬性, Mammal m = new Mammal();

C. BabyRaccoon is-a Mammal. //BabyRaccoon 繼承了 Mammal

D. BabyRaccoon is-a Raccoon. //BabyRaccoon 沒有繼承 Raccoon

E. BabyRaccoon has-a Mammal. // BabyRaccoon 沒有Mammal的屬性 (空的)

F. BabyRaccoon is-a BabyRaccoon. //自己是自己.

第31題

Given:

1. public class Base{
2. public static final String FOO = "foo";
3. public static void main(String[] args){
4. Base b = new Base();
5. Sub s = new Sub();
6. System.out.print(Base.FOO);
7. System.out.print(Sub.FOO);
8. System.out.print(b.FOO);
9. System.out.print(s.FOO);
10. System.out.print(((Base)s).FOO);
11. }
12. }
13. class Sub extends Base{public static final String FOO = "bar";}
What is the result?
A. foofoofoofoofoo
B. foobarfoobarbar
C. foobarfoofoofoo
D. foobarfoobarfoo
E. barbarbarbarbar
F. foofoofoobarbar
G. foofoofoobarfoo

答案:D
參考:6-5 繼承、8-1 變數種類與其生命期

-------------------------------------------
ANS:

6. System.out.print(Base.FOO); //output foo
7. System.out.print(Sub.FOO); //output bar
8. System.out.print(b.FOO); // output foo
9. System.out.print(s.FOO); //output bar
10. System.out.print(((Base)s).FOO); //output foo , s.FOO cast(轉型) to Base. s.FOO 是call 屬性 不是方法.

第30題

Given:

1. public class SimpleCalc{
2. public int value;
3. public void calculate(){value += 7;}
4. }
And:

1. public class MultiCalc extends SimpleCalc{
2. public void calculate(){value -= 3;}
3. public void calculate(int multiplier){
4. calculate();
5. super.calculate();
6. value *= multiplier;
7. }
8. public static void main(String[] args){
9. MultiCalc calculator = new MultiCalc();
10. calculator.calculate(2);
11. System.out.println("Value is: " + calculator.value);
12. }
13. }
What is the result?
A. Value is: 8
B. Compilation fails.
C. Value is: 12
D. Value is: -12
E. The code runs with no output.
F. An exception is thrown at runtime.


答案:A
參考:6-5 繼承

------------------------------------------
Ans:

SCJP 5.0 Question 28.

第42題

1. class A{
2. public String doit(int x, int y){
3. return "a";
4. }
5.
6. public String doit(int... vals){
7. return "b";
8. }
9. }
Given:
25. A a = new A();
26. System.out.println(a.doit(4, 5));
What is the result?
A. Line 26 prints "a" to System.out.
B. Line 26 prints "b" to System.out.
C. An exception is thrown at runtime.
D. Compilation of class A will fail due to an error in line 6.
答案:A
參考:6-2 Java方法


26. System.out.println(a.doit(4, 5));
//會去找看看class A中是否有傳入參數為int,int的,有的就優先呼叫

第41題

1. public class KungFu{
2. public static void main(String[] args){
3. Integer x = 400;
4. Integer y = x;
5. x++;
6. StringBuilder sb1 = new StringBuilder("123");
7. StringBuilder sb2 = sb1;
8. sb1.append("5");
9. System.out.println((x == y) + " " + (sb1 == sb2));
10. }
11. }
What is the result?
A. true true
B. false true
C. true false
D. false false
E. Compilation fails.
F. An exception is thrown at runtime.
----------------------------------------------------------------------------------
答案:B
參考:6-2 Java方法、11-2 文字類型
物件參照到觀念

1. public class KungFu{
2. public static void main(String[] args){
3. Integer x = 400;
4. Integer y = x;
5. x++; //x=x+1 此時y =400,x=new Integer(401)
6. StringBuilder sb1 = new StringBuilder("123");
7. StringBuilder sb2 = sb1;
8. sb1.append("5");
9. System.out.println((x == y) + " " + (sb1 == sb2));
10. }
11. }

第40題

Given:
1. class Foo{
2. private int x;
3. public Foo(int x){this.x = x;}
4. public void setX(int x){this.x = x;}
5. public int getX(){return x;}
6. }
7.
8. public class Gamma{
9. static Foo fooBar(Foo foo){
10. foo = new Foo(100);
11. return foo;
12. }
13. public static void main(String[] args){
14. Foo foo = new Foo(300);
15. System.out.print(foo.getX() + "-");
16.
17. Foo fooFoo = fooBar(foo);
18. System.out.print(foo.getX() + "-");
19. System.out.print(fooFoo.getX() + "-");
20.
21. foo = fooBar(fooFoo);
22. System.out.print(foo.getX() + "-");
23. System.out.print(fooFoo.getX());
24. }
25. }
What is the output?
A. 300-100-100-100-100
B. 300-300-100-100-100
C. 300-300-300-100-100
D. 300-300-300-300-100

---------------------------------------------------------------------------
答案:B
參考:6-2 Java方法、8-2 方法種類與呼叫方式

物件參照到實體的觀念
8. public class Gamma{
9. static Foo fooBar(Foo foo){
10. foo = new Foo(100);
11. return foo;
12. }
13. public static void main(String[] args){
14. Foo foo = new Foo(300);
15. System.out.print(foo.getX() + "-"); //300-
16.
17. Foo fooFoo = fooBar(foo);
18. System.out.print(foo.getX() + "-"); //300-
19. System.out.print(fooFoo.getX() + "-"); //100-
20.
21. foo = fooBar(fooFoo);
22. System.out.print(foo.getX() + "-"); //100-
23. System.out.print(fooFoo.getX()); //100
24. }
25. }

第39題

Given:
11. public class ItemTest{
12. private final int id;
13. public ItemTest(int id){this.id = id;}
14. public void updateId(int newId){id = newId;}
15.
16. public static void main(String[] args){
17. ItemTest fa = new ItemTest(42);
18. fa.updateId(69);
19. System.out.println(fa.id);
20. }
21. }
Which four statments are true? (Choose four.)
A. Compilation fails.
B. An exception is thrown at runtime.
C. The attribute id in the ItemTest object remains unchanged.
D. The attribute id in the ItemTest object is modified to the new value.
E. A new ItemTest object is created with the preferred value in the id attribute.

------------------ ------------------------------------------------------------------
答案:A
參考:6-5 繼承


12. private final int id;
13. public ItemTest(int id){this.id = id;} //正確,建構式可改寫final 變數
14. public void updateId(int newId){id = newId;} //錯誤,不是建構式卻想改寫final 變數

第38題

1. class One{
2. public One foo(){return this;}
3. }
4. class Two extends One{
5. public One foo(){return this;}
6. }
7. class Three extends Two{
8. //insert method here
9. }
Which two methods, inserted individually, correctly complete the Three class? (Choose two.)
A. public void foo(){}
B. public int foo(){return 3;}
C. public Two foo(){return this;}
D. public One foo(){return this;}
E. public Object foo(){return this;}

-----------------------------------------------------------------------------------
答案:CD
參考:6-5 繼承
繼承及改寫的觀念
A. public void foo(){} //試圖改寫第5行但回傳是錯的
B. public int foo(){return 3;} //試圖改寫第5行但回傳是錯的
C. public Two foo(){return this;}
D. public One foo(){return this;}
E. public Object foo(){return this;} //試圖改寫第5行但回傳是錯的

第37題

Given:
21. abstract class C1{
22. public C1(){System.out.print(1);}
23. }
24. class C2 extends C1{
25. public C2(){System.out.print(2);}
26. }
27. class C3 extends C2{
28. public C3(){System.out.print(3);}
29. }
30. public class Ctest{
31. public static void main(String[] a){new C3();}
32. }
What is the result?
A. 3
B. 23
C. 32
D. 123
E. 321
F. Compilation fails.
G. An exception is thrown at runtime.


------------------------------------------------------------------------------
答案:D
參考:6-5 繼承

目的考建構式的觀念,
31. public static void main(String[] a){new C3();}
>>27. class C3 extends C2{
>>>>24. class C2 extends C1{
>>>>>>21. abstract class C1{
>>>>>>>>22. public C1(){System.out.print(1);}
>>>>>>>>>>25. public C2(){System.out.print(2);}
>>>>>>>>>>>>28. public C3(){System.out.print(3);}

2009年2月5日 星期四

第36題

Given:
public class Doubler{
public static int doubleMe(Holder h){
return h.getAmount() * 2;
}
}
and:
public class Holder {
int amount = 10;
public void doubleAmount(){amount = Doubler.doubleMe(this);}
public in getAmount(){return amount;}
//more code here
}
Place the code framgmets in position to reduce the coupling between Doubler and Holder.
public class Doubler{
public static int doubleMe( Place here h){
return Place here * 2;
}
}
public class Holder {
int amount = 10;
public void doubleAmount(){amount = Doubler.doubleMe( Place here );}


public in getAmount(){return amount;}
//more code here
}
Code Fragments
void
Holder
int
Doubler
h.getAmount()

h
this
amount
-----------------------------------------------------------------------------------------
答案:

public class Doubler{


public static int doubleMe( int h){

return h * 2;


}
}

public class Holder{

int amount = 10;

public void doubleAmount(){amount = Doubler.doubleMe( amount );}

public int getAmount(){return amount;}
//more code here

}

參考:6-2 Java方法

原code傳入物件,目的只是為了計算 amount
public void doubleAmount(){amount = Doubler.doubleMe(this);}
...
return h.getAmount() * 2;

修改後code,只需傳入amount即可降低相依性

第29題

Given:
1. public class A{
2. public void doit(){
3. }
4. public String doit(){
5. return "a";
6. }
7. public double doit(int x){
8. return 1.0;
9. }
10. }

What is the result?

A. An exception is thrown at runtime.
B. Compilation fails because of an error in line 7.
C. Compilation fails because of an error in line 4.
D. Compilation succeeds and no runtime errors with class A occur.

答案:C
參考:6-5 繼承

----------------------------------------------
ANS:

Duplicate method doit() in type A

Test - Alert

第28題

Given:
1. class X{
2. X(){System.out.print(1);}
3. X(int x){
4. this();
5. System.out.print(2);
6. }
7. }
8. public class Y extends X{
9. Y(){
10. super(6);
11. System.out.print(3);
12. }
13. Y(int y){
14. this();
15. System.out.println(4);
16. }
17. public static void main(String[] a){new Y(5);}
18. }
What is the result?
A. 13
B. 134
C. 1234
D. 2134
E. 2143
F. 4321

-----------------------------------------------------------------------------------------------
答案:C
參考:6-5 繼承

17. public static void main(String[] a){new Y(5);}
>>8. public class Y extends X{
>>13. Y(int y){
>>>>9. Y(){
>>>>10. super(6);
>>>>>> 3. X(int x){
>>>>>> 4. this();
>>>>>>>> 2. X(){System.out.print(1);} //output 1
>>>>>>>> 5. System.out.print(2); //output 2
>>>>>>>> 11. System.out.print(3); //output 3
>>>>>>>> 15. System.out.println(4); //output 4

第27題

Given:

10. class One{
11. void foo(){}
12. }
13. class Two extends One{
14. //insert method here
15. }
Which three methods, inserted individually at line 14, will correctly complete class Two? (Choose three.)
A. int foo(){/* more code here */}
B. void foo(){/* more code here */}
C. public void foo(){/* more code here */}
D. private void foo(){/* more code here */}
E. protected void foo(){/* more code here */}


-----------------------------------------------------------------------------------------------
答案:BCE
參考:6-5 繼承
第14行要插入什麼程式才能編譯成功
A. int foo(){/* more code here */} //回傳類型不符規則
D. private void foo(){/* more code here */} //private小於原有的開放程度

第26題

10. interface Jumper{public void jump();}
...
20. class Animal{
}
..
.
30. class Dog extends Animal{
31. Tail tail;
32.
}
..
.
40. class Beagle extends Dog implements Jumper{
41. public void jump(){}
42.
}
..
.
50. class Cat implements Jumper{
51. public void jump(){}
52. }
Which three are true? (Choose three.)
A. Cat is-a Animal
B. Cat is-a Jumper
C. Dog is-a Animal
D. Dog is-a Jumper
E. Cat has-a Animal
F. Beagle has-a Tail
G. Beagle has-a Jumper




-------------------------------------------------------------------------------------
答案:BCF
參考:6-5 繼承
A. Cat is-a Animal //題目中Cat和Animal沒任何關係
B. Cat is-a Jumper //Cat是Jumper的子類別 50. class Cat implements Jumper{
C. Dog is-a Animal //Dog和Animal 是父子關關 30. class Dog extends Animal{
D. Dog is-a Jumper //題目中Dog和Jumper沒任何關係
E. Cat has-a Animal //題目中 Cat的屬性中沒有任何一類別為Animal 51. public void jump(){}
F. Beagle has-a Tail //看起來Beagle沒有Tail的屬性,可是Beagle繼承Dog,Dog有Tail的屬性所以等同Beagle有Tail
G. Beagle has-a Jumper //題目中Beagle沒有Jumper的屬性

W3School CSS Tutorial

http://www.w3schools.com/css/default.asp

Tutorial:
http://www.w3schools.com/css/css_intro.asp

Examples:
http://www.w3schools.com/css/css_examples.asp

Quiz:
http://www.w3schools.com/css/css_quiz.asp

Reference:
http://www.w3schools.com/css/css_reference.asp

第25題

Given:
1. class ClassA{
2. public int numberOfInstances;
3. protected ClassA(int numberOfInstances){
4. this.numberOfInstances = numberOfInstances;
5. }
6. }
7. class ExtendedA extends ClassA{
8. private ExtendedA(int numberOfInstances){
9. super(numberOfInstances);
10. }
11. public static void main(String[] args){
12. ExtendedA ext = new ExtendedA(420);
13. System.out.print(ext.numberOfInstances);
14. }
15. }
What is the result?
A. 420 is the output
B. An exception is thrown at runtime.
C. All constructors must be declared public.
D. Constructors CANNOT use the private modifier.
E. Constructors CANNOT use the protected modifier.


-----------------------------------------------------------------------------------------------
答案:A
參考:6-5 繼承
考建構式的觀念
11. public static void main(String[] args){
12. ExtendedA ext = new ExtendedA(420);
>>
8. private ExtendedA(int numberOfInstances){ //420
9. super(numberOfInstances); //420
>>
3. protected ClassA(int numberOfInstances){ //420
4. this.numberOfInstances = numberOfInstances; //420
>>
2. public int numberOfInstances; //420
>>
13. System.out.print(ext.numberOfInstances); //420

W3Schools Online Web Tutorial 線上教學

http://www.w3schools.com/default.asp

著名的線上教學網頁,裡面有HTML,XHTML,CSS,JAVASCRIPT,SQL,PHP...等,大部分的網頁編碼教學.
有Try-it-yourself ONLINE EXAMPLES 可以直接測試CODES, Online Quiz(線上測驗) 和 線上認證.

JavaScript test

Test

第24題

A company that makes Computer Assisted Design(CAD) software has, within its application some utility classes that are used to perform 3D rendering tasks. The company's chief scientist has just improved the performance of one of the utility classes' key rendering algorithms, and has assigned a programmer to replace the old algorithm with the new algorithm. When the programmer begins researching the utility classes, she is happy to discover that the algorithm to be replaced exists in only one class. The programmer reviews that class's API, and replaces the old algorithm with the new algorithm, being careful that her changes adhere strictly to the class's API. Once testing has begun, the programmer discovers that other classes that use the class she changed are no longer working properly. What design flaw is most likely the cause of there new bugs?
A. Inheritance
B. Tight coupling
C. Low cohesion
D. High cohesion
E. Loose coupling
F. Object immutablility



-----------------------------------------------------------------------------------------------
答案:B
參考:第6 章物件導向基本觀念

有間公司寫了一個CAD的軟體,想要更新一些功能,就請一位工程師去看程式碼看需修改什麼,工程師看後發現只需修改其中的一個class的演算法就可以了,當工程師修改後進行測試時發現所有的功能都無法運作,何者的系統設計的序述較符合這bug的情況?
B. Tight coupling //高相依性

JavaScript 及CSS的教學投影片

今天整理JavaScript時無意中發現一個網頁
在網頁的最下方有JavaScript 及 CSS 的教學投影片

可以直接在線上作投影!!

有興趣的人可到下列網址看看!!

http://blog.ericsk.org/archives/1057

第23題

A company has a business application that provides its users with many different reports: receivables reports, payables reports, revenue projects, and so on. The company has just purchased some new, state-of-the-art, wireless printers, and a programmer has been assigned the task of enhancing all of the reports to use not only the company's old printers, but the new wireless printers as well. When the programmer starts looking into the application, the programmer discovers that because of the design of the application, it is necessary to make changes to each report to support the new printers. Which two design concepts most likely explain the situation? (Choose two.)
A. Inheritance
B. Low cohesion
C. Tight coupling
D. High cohesion
E. Loose coupling
F. Object immutablility




-----------------------------------------------------------------------------------------------
答案:BC
參考:第6 章物件導向基本觀念

有間公司有個商業應用系統這系統提供了各式各樣的報表功能.這間公司剛採購了新的無線印表機,並指派了一位工程師去看能否將報表功能支援原有的印表機及新的無線印表機.當這位工程師去看了程式碼後發現,如要支援新的無線印表機時,將要修改每一支報表的程式.
Low cohesion //低凝聚性 Tight coupling //高相依性

第22題

Given:
1. class Pass{
2. public static void main(String[] args){
3. int x= 5;
4. Pass p = new Pass();
5. p.doStuff(x);
6. System.out.print(" main x = " + x);
7. }
8. void doStuff(int x){
9. System.out.println(" doStuff x = " + x++);
10. }
11. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. doStuff x = 6main x = 6
D. doStuff x = 5main x = 5
E. doStuff x = 5main x = 6
F. doStuff x = 6main x = 5


-----------------------------------------------------------------------------------------------
答案:D
參考:6-2 Java方法
說明:
這題主要考傳值的觀念,
3. int x= 5; //給預設值
...
5. p.doStuff(x);//呼叫 doStuff
...
8. void doStuff(int x){ //將值傳入
9. System.out.println(" doStuff x = " + x++); //先將x print出來後再做+1的動作
(doStuff x = 5)
//第9行執行過後變數x的值不會改變
...
繼續執行
6. System.out.print(" main x = " + x);
(main x = 5)

2009年2月4日 星期三

第21題SampleCode

Given:
1. class Batman{
2. int squares = 81;
3. public static void main(String[] args){
4. new Batman().go();
5. }
6. void go(){
7. incr(++squares);
8. System.out.println(squares);
9. }
10. void incr(int squares){squares += 10;}
11. }

What is the result?

A. 81
B. 82
C. 91
D. 92
E. Compilation fails.
F. An exception is thrown at runtime.

答案:B
參考:6-2 Java 方法

第20題SampleCode

A team of programmers is reviewing a proposed API for a new utility class. After some discussion, they realize that they can reduce the number of methods in the API without losing any functionality. If they implement the new design, which two OO principles will they be promoting?
A. Looser coupling
B. Tighter coupling
C. Lower cohesion
D. Higher cohesion
E. Weaker encapsulation
F. Stronger encapsulation

答案:AD
參考:第6 章 物件導向基本觀念

----------------------------------------------------------------------

http://www.javaonnet.com/2005/12/coupling-and-cohesion.html
http://javaboutique.internet.com/tutorials/coupcoh/

第19題SampleCode

Which Man class properly represents the relationship "Man has a best friend who is a Dog"?

A. class Man extends Dog{}
B. class Man implements Dog{}
C. class Man{private BestFriend dog;}
D. class Man{private Dog bestFriend;}
E. class Man{private Dog;}
F. class Man{private BestFriend;}

答案:D

參考:6-5 繼承

----------------------------------------------------

第18題SampleCode

Given:
1. class Super{
2. private int a;
3. protected Super(int a){this.a = a;}
4. }
...
11. class Sub extends Super{
12. public Sub(int a){super(a);}
13. public Sub(){this.a = 5;}
14. }

Which two, independently, will allow Sub to compile? (Choose two.)
A. Change line 2 to:public int a;
B. Change line 2 to:protected int a;
C. Change line 13 to:public Sub(){this(5);}
D. Change line 13 to:public Sub(){super(5);}
E. Change line 13 to:public Sub(){super(a);}

答案:CD
參考:6-5 繼承

---------------------------------------------------------------
class Super{
private int a;
// public int a;
// protected int a;
protected Super(int a){this.a = a;}
}

class Sub extends Super{
public Sub(int a){super(a);}

// public Sub(){this(5);}
// public Sub(){super(5);}
// public Sub(){super(a);} //Cannot refer to an instance field a while explicitly invoking a constructor
public Sub(){this.a = 5;} //Implicit super constructor Super() is undefined. Must explicitly invoke another constructor
}

第17題SampleCode

Given:
1. public class Blip{
2. protected int blipvert(int x){return 0;}
3. }
4. class Vert extends Blip{
5. //insert code here
6. }

Which five methods, inserted independently at line 5, will compile? (Choose five.)
A. public int blipvert(int x){return 0;}
B. private int blipvert(int x){return 0;}
C. private int blipvert(long x){return 0;}
D. protected long blipvert(int x){return 0;}
E. protected int blipvert(long x){return 0;}
F. protected long blipvert(long x){return 0;}
G. protected long blipvert(int x, int y){return 0;}

答案:ACEFG
參考:6-5 繼承

-------------------------------------------------------------------------
public class Blip {
protected int blipvert(int x) {
return 0;
}
}
class Vert extends Blip{
public int blipvert(int x){return 0;}
private int blipvert(int x){return 0;} //Cannot reduce the visibility of the inherited method
private int blipvert(long x){return 0;}
protected long blipvert(int x){return 0;} //The return type is incompatible
protected int blipvert(long x){return 0;}
protected long blipvert(long x){return 0;}
protected long blipvert(int x, int y){return 0;}
}

第16題SampleCode

Given:
5. class Atom{
6. Atom(){System.out.print("atom ");}
7. }
8. class Rock extends Atom{
9. Rock(String type){System.out.print(type);}
10. }
11. public class Mountain extends Rock{
12. Mountain(){
13. super("granite ");
14. new Rock("granite ");
15. }
16. public static void main(String[] a){new Mountain();}
17. }

What is the result?
A. Compilation fails.
B. atom granite
C. granite granite
D. atom granite granite
E. An exception is thrown at runtime.
F. atom granite atom granite

答案:F

--------------------------------------------------------------------------
class Atom{
Atom(){System.out.print("atom ");}
}
class Rock extends Atom{
Rock(String type){System.out.print(type);}
}
public class Mountain extends Rock{
Mountain(){
super("granite ");
new Rock("granite ");
}
public static void main(String[] a){new Mountain();}
}

第15題SampleCode

Given:

11. class Mud{
12. //insert code here
13. System.out.println("hi");
14. }
15. }

And the following five fragments:

public static void main(String...a){
public static void main(String.* a){
public static void main(String... a){
public static void main(String[]... a){
public static void main(String...[] a){

How many of the code fragments, inserted independently at line 12, compile?
A. 0
B. 1
C. 2
D. 3
E. 4
F. 5

答案:D

參考:6-2 Java 方法
---------------------------------------
public static void main(String...a){
public static void main(String.* a){ //Syntax error on token "*", Identifier expected
public static void main(String... a){
public static void main(String[]... a){
public static void main(String...[] a){ //Syntax error on token "...", delete this token

2009年2月3日 星期二

第7題SampleCode

Given:
1. public class Breaker2{
2. static String o = "";
3. public static void main(String[] args){
4. z:
5. for(int x=2; x<7; x++){
6. if(x == 3) continue;
7. if(x == 5) break z;
8. o = o + x;
9. }
10. System.out.println(o);
11. }
12. }

What is the result?
A. 2
B. 24
C. 234
D. 246
E. 2346
F. Compilation fails.
答案:B
參考:4-3 特殊流程的處理

------------------------------------------------
My Answers:
2
4
5
24


------------------------------------------------

第6題SampleCode

Given:
1. public class Breaker{
2. static String o = "";
3. public static void main(String[] args){
4. z:
5. o = o + 2;
6. for(int x=3; x<8; x++){
7. if(x == 4) break;
8. if(x == 6) break z;
9. o = o + x; 10. }
11. System.out.println(o);
12. }
13. }
What is the result?
A. 23
B. 234
C. 235
D. 2345
E. 2357
F. 23457
G. Compilation fails.

答案:G
參考:4-3 特殊流程的處理
---------------------------------------------------
My Answers:
The label z is missing
Correction:
o = o + 2;
z:
Label和下面的迴圈語句間不能有其他代碼。
---------------------------------------------------

第5題SampleCode

Given:
10. int x = 0;
11. int y = 10;
12. do{
13. y--;
14. ++x;
15. }while(x < 5);
16. System.out.print(x + "," + y);

What is the result?
A. 5,6
B. 5,5
C. 6,5
D. 6,6

答案:B
參考:4-2 迴圈控制

--------------------------------------
My Answers:
Y=10 X=0
Y=9 X=1
-----1-----
Y=9 X=1
Y=8 X=2
-----2-----
Y=8 X=2
Y=7 X=3
-----3-----
Y=7 X=3
Y=6 X=4
-----4-----
Y=6 X=4
Y=5 X=5
-----5-----
5,5
------------------------------------------

HTML


    資料來源為:http://www.csie.nctu.edu.tw/~jglee/teacher/content.htm


  • HTML外觀
    <html>

    <head>

    <title>名稱</title>

    </head>

    <body>

    內容

    </body>

    </html>


    Titile讓首頁製作者以簡短的文字表達此一首頁之內容。Title的內容會出現在瀏覽器的頂端。若將某個首頁加入書籤,則Title內容變成該書籤名稱。


    標題
    <html>
    <head><title>標題測試</title></head>
    <body> <center>
    <h1>第一級標題</h1>正常文字
    <h2>第二級標題</h2>正常文字
    <h3>第三級標題</h3>正常文字
    <h4>第四級標題</h4>正常文字
    <h5>第五級標題</h5>正常文字
    <h6>第六級標題</h6>正常文字
    </center> </body>
    </html>









  • 字型

  • 基本格式

    <font size=n color=顏色>字串

範例:<font size=7 color=white>南</font>





  • 換行小常識


當您看到的中文字無法依視窗大小而自動斷行時,只要將:Options的Document Encoding設成Traditional Chinese(Big-5)就可以了!





  • 斜體字


範例:標準字<i>斜體字</i>標準字





  • 粗體字


範例:標準字< b>粗體字</b>標準字





  • 底線字


範例:標準字<u>底線字</u>標準字





  • 表格(製作表格)


<table border=n>



<caption>表格標題</caption>



<tr><td>列一行一</td><td>列一行二</td></tr><tr><td>列二行一</td><td>列二行二</td></tr>



</table>





  • 表格(合併儲存格)


你可以用ROWSPAN=n及COLSPAN=n來完成



例如:<th colspan=2>大雄的功課表</th><th rowspan=4>上午</th><td rowspan=4>沒<br>課</td>



  • 圖片

放在WWW上的圖片必須是附加檔名為gif或jpg


格式:<img src="路徑/圖檔檔名"alt="找不到圖檔時出現的內容,當滑鼠移到圖片上方時也會出現該內容"width=XX顯示時的寬度height=XX顯示時的高度border="邊框大小">


範例:<img src="images/nor2.jpg"alt="酒井法子的相片">


範例:<img src="images/nor2.jpg"alt="酒井法子的相片"border=0>




  • 圖片連結

點選圖片可連結到另一個網頁


<map name="map-name">


<area shape=形狀 coords="座標" href="連到哪裡去">


<area shape=形狀 coords="座標" href="連到哪裡去">


...


</map><img src="xxx" usemap="#map-name">












第4題SampleCode

Given:
22. public void go(){
23. String o = "";
24. z:
25. for(int x=0; x<3; x++){
26. for(int y=0; y<2; y++){
27. if(x == 1) break;
28. if(x==2 && y==1) break z;
29. o = o + x + y; 30. }
31. }
32. System.out.println(o);
33. }

What is the result when the go() method is invoked?
A. 00
B. 0001
C. 000120
D. 00012021
E. Compilation fails.
F. An exception is thrown at runtime.
答案:C
參考:4-3 特殊流程的處理
---------------------------------------
My Answers:
X loop
Y loop
x = 0 y = 0
00
Y loop
x = 0 y = 1
0001
X loop
Y loop
x = 1 y = 0
X loop
Y loop
x = 2 y = 0
000120
Y loop
x = 2 y = 1
000120

-------------------------------------

第3題SampleCode

Given:
1. public class Test{
2. public static void main(String[] args){
3. int x = 5;
4. boolean b1 = true;
5. boolean b2 = false;
6.
7. if((x==4) && !b2)
8. System.out.print("1 ");
9. System.out.print("2 ");
10. if((b2=true) && b1)
11. System.out.print("3 ");
12. }
13. }

What is the result?
A. 2
B. 3
C. 1 2
D. 2 3
E. 1 2 3
F. Compilation fails.
G. An exception is thrown at runtime.
答案:D
參考:4-1 條件控制

--------------------------------------------
public class SCJP6003 {
public static void main(String[] args) {
int x= 5;
boolean b1 = true;
boolean b2 = false;

if((x==4) && !b2)
System.out.print("1 ");
System.out.print("2 ");
if((b2=true) && b1)
System.out.print("3 ");
}
}

ANS:
D. 2 3

--------------------------------------------------------------------------------------
My Answers:
7. if((x==4) && !b2)
8. System.out.print("1 ");
will not run coz, x not equals 4
--------------------------------------------------------------------------------------

Javascript實例教程 日期函數

var today = new Date();

返回當前的日期和時間

var newyear = new Date("December 31, 1998 23:59:59");

輸入的是表單的字符串 「月 日,年 小時:分鐘:秒」

var bday = new Date(75, 1, 16);

參數是年份,月,日

var bday = new Date(75, 1, 16, 12, 0, 0);

參數是年份,月,日,小時,分鐘,秒


這裡作點補充:月份是從0開始的,比如一月份=0,二月份=1,三月份=3等等。
從上面可以看出創建一個日期對象是相對地簡單,以下的表格是一系列的函數可以用於改變或者訪問這些對象的屬性:
日期訪問方法

Method(方法)

Description (描述)

Value(數值)

getYear()

返回年份的最後兩位數字

2001

getMonth()

返回年份中的第幾月(0到11)

5

getDate()

返回月份中的第幾日(1到31)

2

getDay()

返回星期中的第幾天 (0到6)

6

getTimezoneOffset()

返回當地時間與格林尼治天文台平均時間的差別

-480 (-8h)

getHours()

返回一天中的時針點數(0到23)

16

getMinutes()

返回分鐘 (0..59)

8

getSeconds()

返回時間的秒 (0到59)

24

getTime()

返回自從公元1970年1月1日的毫秒數

991469304470


這裡注意:IE瀏覽器的一些版本返回Timezoneoffset數值是用錯誤的符號,比如用」-」代替」+」等等。
日期設置方法

setDate()

設置每月中的第幾天(從0到30)

setHours()

設置小時(從0到23)

setMinutes()

設置分鐘(從0到59)

setMonth()

設置月份(從0到11)

setSeconds()

設置秒數(從0到59)

setTime()

設置時間(從公元以來的毫秒數)

setYear()

設置年份


其它的日期方法

parse

轉化日期字符串為自從公元以來的毫秒數,比如Date.parse(「date string」)

toString()

Sat Jun 2 16:08:24 UTC+0800 2001

toGMTString()

Sat, 2 Jun 2001 08:08:24 UTC

toLocaleString()

2001年6月2日 16:08:24


所有的這些函數引用於獨立的日期對象。
如果你具有深厚的Java編程背景,那麼你可以將它們認為是Date類的一些公共的方法而已。

下面給出一個典型的例子來設置日期對像到當前時間加1年:

var nextYear = new Date(); // 初始化日期對像

nextyear.setYear(nextYear.getYear() + 1); // 增加1年實際上,

parse函數是Date對象的一個方法,而不是一個獨立的日期變量,如果使用Java術語,它就稱為Date類的一個靜態方法。
這個正是我們為什麼使用Date.pase()而不使用somedate.parse()的原因啦。

資料來源:http://www.knowsky.com/3615.html

第2題SampleCode

Given:
1. public class TestString1{
2. public static void main(String[] args){
3. String str = "420";
4. str += 42;
5. System.out.print(str);
6. }
7. }
What is the output?
A. 42
B. 420
C. 462
D. 42042
E. Compilation fails.
F. An exception is thrown at runtime.
答案:D
參考:3-3 文字串接符號


------------------------------------------------
public class SCJP6002 {
public static void main(String[] args) {
String str = "420";
str += 42;
System.out.print(str);
}
}

ANS:
D. 42042
-------------------------------------------------------------------------------------
My Answers:
Str = str + 42 == ( 420+42) == 42042
-------------------------------------------------------------------------------------

第1題SampleCode

Given:
35. String #name = "Jane Doe";
36. int $age = 24;
37. Double _height = 123.5;
38. double ~temp = 37.5;
Which two statements are true? (Choose two.)
A. Line 35 will not compile.
B. Line 36 will not compile.
C. Line 37 will not compile.
D. Line 38 will not compile.
答案:AD
參考:2-4 Java 程式內容簡介

------------------------------------------------------
public class SCJP6001 {
public static void main(String[] args) {
String #name = "Jane Doe";
int $age = 24;
Double _height = 123.5;
double ~temp = 37.5;
}
}

ANS:
A. Line 35 will not compile.
D. Line 38 will not compile.
-------------------------------------------------------------------------------------
My Answers:
35. String #name = "Jane Doe";
Syntax error on token "Invalid Character", delete this token
38. double ~temp = 37.5;
Syntax error on token "~", delete this token


Java variable names must start with one of the following characters:
• Letter
• Underscore
• Dollar sign
-------------------------------------------------------------------------------------

第14題 SampleCode

11. class Person{
12. String name = "No name";
13. public Person(String nm){name = nm;}
14. }
15.
16. class Employee extends Person{
17. String empID = "0000";
18. public Employee(String id){empID = id;}
19. }
20.
21. class EmployeeTest{
22. public static void main(String[] args){
23. Employee e = new Employee("4321");
24. System.out.println(e.empID);
25. }
26. }
What is the result?
A. 4321
B. 0000
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 18.
---------------------------------------------------------------------
答案:D



class test14{
String name = "No name";
public test14(String nm){name = nm;}
}
class Employee extends test14{
String empID = "0000";
public Employee(String id){empID = id;}
}
//Implicit super constructor test14() is undefined.
//Must explicitly invoke another constructor

class EmployeeTest{
public static void main(String[] args){
Employee e = new Employee("4321");
System.out.println(e.empID);
}
}

ANS:
D. Compilation fails because of an error in line 18.

--------------------------------------------------------------------------------------
error msg
Implicit super constructor test14() is undefined. Must explicitly invoke another constructor

第13題 SampleCode

1. public class Barn{
2. public static void main(String[] args){
3. new Barn.go("hi", 1);
4. new Barn.go("hi", "world", 2);
5. }
6. public void go(String... y, int x){
7. System.out.print(y[y.length-1] + " ");
8. }
9. }
What is the result?
A. hi hi
B. hi world
C. world world
D. Compilation fails.
E. An exception is thrown at runtime.
-------------------------------------------------------------------------------
答案:D

public class test13 {
public static void main(String[] args) {
new test13.go("hi",1); new test13.go("hi", "world",2);
}
//The variable argument type String of the method go
//must be the last parameter
public void go( String...y,int x) {
System.out.print(y[y.length - 1] + " ");
}
}

ANS:
D. Compilation fails.
---------------------------------------------------------------------------
error msg
The variable argument type String of the method go must be the last parameter

第12題 SampleCode

Drag and Drop(拖曳題

Add methods to the Beta class to make it compile correctly.


Methods

class Alpha{
public void bar(int... x){}
public void bar(int x){}
}
public class Beta extends Alpha{
Place here
Place here
Place here

}
private void bar(int x){}
public void bar(int x){}
public int bar(String x){return 1;}
public Alpha bar(int x){}
public void bar(int x, int y){}
public int bar(int x){return x;}
答案:

class Alpha{
public void bar(int... x){}
public void bar(int x){}

}

public class Beta extends Alpha{

public void bar(int x){}
public int bar(String x){return 1;}
public void bar(int x, int y){}


}

class test12{

class Alpha{
public void bar(int... x){}
public void bar(int x){}
}

public class Beta extends Alpha{

public void bar(int x){}
public int bar(String x){return 1;}
public void bar(int x, int y){}
}
}

ANS:
public void bar(int x){}
public int bar(String x){return 1;}
public void bar(int x, int y){}

第11題 SampleCode

1. class Alligator{
2. public static void main(String[] args){
3. int[]x[] = {{1,2},{3,4,5},{6,7,8,9}};
4. int[][]y = x;
5. System.out.print(y[2][1]);
6. }
7. }
What is the result?
A. 2
B. 3
C. 4
D. 6
E. 7
F. Compilation fails.
----------------------------------------------------------------
答案:E

class test11{
public static void main(String[] args){
int[]x[] = {{1,2},{3,4,5},{6,7,8,9}};
int[][]y = x;
for (int i=0;i for (int j=0;j System.out.print(y[i][j]);
}
System.out.println();
}
System.out.println(y[2][1]);
}
}

ANS:
E. 7
-----------------------------------------------------------------------------
參考輸出如下
12
345
6789

第10題 SampleCode

1. import java.util.*;
2. public class Quest{
3. public static void main(String[] args){
4. String[] colors =
5. {"blue","red","green","yellow","orange"};
6. Arrays.sort(colors);
7. int s2 = Arrays.binarySearch(colors, "orange");
8. int s3 = Arrays.binarySearch(colors, "violet");
9. System.out.print(s2 + "" + s3);
10. }
11. }
What is the result?
A. 2-1
B. 2-4
C. 2-5
D. 3-1
E. 3-4
F. 3-5
G. Compilation fails.
H. An exception is thrown at runtime.
-------------------------------------------------------------------------
答案:C

import java.util.*;
public class test10 {
public static void main(String[] args){
String[] colors =
{"blue","red","green","yellow","orange"};
Arrays.sort(colors);
for (int i=0;i<colors.length ; i++){
System.out.println(colors[i]);
}
//二分搜尋法
int s2 = Arrays.binarySearch(colors, "orange");
int s3 = Arrays.binarySearch(colors, "violet");
System.out.println(s2 + "" + s3);
//從第一個字母依序往後找
}
}

ANS:
C. 2-5

第9題 SampleCode

11. String[] elements = {"for", "tea", "too"};
12. String first = (elements.length>0) ? elements[0] : null;
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The variable first is set to null.
D. The variable first is set to elements[0].
------------------------------------------------------------------------------
答案:D

public class test09 {
public static void main(String[] args){
String[] elements = {"for", "tea", "too"};
String first = (elements.length>0) ? elements[0] : null;
System.out.println(first);
}
}

ANS:
D. The variable first is set to elements[0].

第8題 SampleCode

Given:
1. public class Spock{
2. public static void main(String[] args){
3. Long tail = 2000L;
4. Long distance = 1999L;
5. Long story = 1000L;
6. if((tail>distance) ^ ((story*2)==tail))
7. System.out.print("1");
8. if((distance+1 != tail) ^ ((story*2)==distance))
9. System.out.print("2");
10. }
11. }
What is the result?
A. 1
B. 2
C. 12
D. Compilation fails.
E. No output is produced.
F. An exception is thrown at runtime.

-------------------------------------------------------------------------------------------
答案:E

public class test08 {
public static void main(String[] args){
Long tail = 2000L;
Long distance = 1999L;
Long story = 1000L;
System.out.println("tail= " + tail);
System.out.println("distance= " + distance);
System.out.println("story*2= " + story*2);
System.out.println("----------------------");
if((tail>distance) ^ ((story*2)==tail))
System.out.print("1");
System.out.println("distance+1= " + distance+1);
System.out.println("tail= " + tail);
System.out.println("story*2= " + story*2);
System.out.println("distance= " + distance);
if((distance+1 != tail) ^ ((story*2)==distance))
System.out.print("2"); } }

ANS:
E. No output is produced.

QUESTION 8----String、StringBuffer、StringBuilder

String--特性:immutable(永遠不變), 字串變化可使用運算子「+」或是concat()方法
StringBuffer---特性:mutable ; thread-safe ; 可使用的方法substring()、replace()、delete()
StringBuilder--特性:mutable ;non-thread-safe ; 可使用的方法substring()、replace()、delete()

substring public String substring(int beginIndex, int endIndex)
substring 回傳值為string,
參數:
beginIndex - 起始索引(包括)。
endIndex - 結束索引(不包括)。

但replace()、delete() 回傳值為StringBuffer或StringBuilder

所以substring()與delete()併用時可能會發生錯誤的用法:
EX:
SringBuilder s=new StringBuilder("123456789");
s.substring(0,5).delete(0,3).replace(0,3,"Java");
System.out.println(s);
會造成編譯錯誤(cannot find symbol)!

關於JAVA 5.0 後有多了一種新的迴圈寫法

public class NewFor {
 public static void main(String[] args) {

   String [] a = {"1","3","5","7","9","11"};

//5.0前的for迴圈寫法
   for(int i = 0 ; i < a.length ; i++){
      String temp = a[i];
      System.out.print(temp + ", ");
   }

  System.out.println();

//5.0後for迴圈新的寫法
   for(String temp : a){
      System.out.print(temp + ", ");
  }
 }
}

輸出結果為:

1, 3, 5, 7, 9, 11,
1, 3, 5, 7, 9, 11,

輸出結果為一樣一樣!!

新的for迴圈用於 collection 及 array

Question 1

1.序列化是幹什麼的?
簡單說就是為了保存在記憶體中的各種物件的狀態(也就是實例變數,不是方法),並且可以把保存的物件狀態再讀出來。雖然你可以用你自己的各種各樣的方法來保存object states,但是Java給你提供一種應該比你自己好的保存物件狀態的機制,那就是序列化。
2、什麼情況下需要序列化
a)當你想把的記憶體中的物件狀態保存到一個檔中或者資料庫中時候;
b)當你想用套接字在網路上傳送物件的時候;
c)當你想通過RMI傳輸物件的時候;
3、當對一個物件實現序列化時,究竟發生了什麼?
在沒有序列化前,每個保存在堆(Heap)中的物件都有相應的狀態(state),即實例變數(instance ariable)
比如:
java 代碼
Foo myFoo = new Foo();
myFoo .setWidth(37);
myFoo.setHeight(70);
當 通過下面的代碼序列化之後,MyFoo物件中的width和Height實例變數的值(37,70)都被保存到foo.ser檔中,這樣以後又可以把它從檔中讀出來,重新在堆中創建原來的物件。當然保存時候不僅僅是保存物件的實例變數的值,JVM還要保存一些小量資訊,比如類的類型等以便恢復原來的對 象。
java 代碼
FileOutputStream fs = new FileOutputStream("foo.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(myFoo);
4、實現序列化(保存到一個檔)的步驟
a)Make a FileOutputStream
java 代碼
FileOutputStream fs = new FileOutputStream("foo.ser");
b)Make a ObjectOutputStream
java 代碼
ObjectOutputStream os = new ObjectOutputStream(fs);
c)write the object
java 代碼
os.writeObject(myObject1);
os.writeObject(myObject2);
os.writeObject(myObject3);
d) close the ObjectOutputStream
java 代碼
os.close();
5、舉例說明
java 代碼
import java.io.*;
public class Box implements Serializable {
private int width;
private int height;
public void setWidth(int width){ this.width = width; }
public void setHeight(int height){ this.height = height; }
public static void main(String [] args){
Box myBox = new Box();
myBox.setWidth(50);
myBox.setHeight(30);
try{
FileOutputStream fs = new FileOutputStream("foo.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(myBox);
os.close();
}catch(Exception ex){ ex.printStackTrace(); }
}
}
6、相關注意事項
a)序列化時,只對物件的狀態進行保存,而不管物件的方法;
b)當一個父類實現序列化,子類自動實現序列化,不需要顯式實現Serializable介面;
c)當一個物件的實例變數引用其他物件,序列化該物件時也把引用物件進行序列化;
d)並非所有的物件都可以序列化,,至於為什麼不可以,有很多原因了,比如:
1.安全方面的原因,比如一個物件擁有private,public等field,對於一個要傳輸的物件,比如寫到檔,或者進行rmi傳輸 等等,在序列化進行傳輸的過程中,這個物件的private等域是不受保護的。
2. 資源分配方面的原因,比如socket,thread類,如果可以序列化,進行傳輸或者保存,也無法對他們進行重新的資源分 配,而且,也是沒有必要這樣實現。

Question 5

The doesFileExist method takes an array of directory names representing a path from the root filesystem and a filename.The

method returns true if the file exists,false if does not.

Place the code fragments in position to complete this method.

//insert here A
for(String dir:directories){
//insert here B
}

//insert here C

//insert here D

Code Fragments

1.path = path.getSubdirectory(dir);
2.return !file.inNew();
3.return (file!=null);
4.String path="";
5.path = path.getFile(filename);
6.File path = new File("");
7.return file.exist();
8.return path.isFile();
9.File file = new File(path,filename);
10.path = new File(path,dir);
11.File path = new File(File.separator);
12.path = path+FileSeparator+dir;

當然了,要想做出這道題目,首先要知道這個程式段想要做什麼,要完成什麼任務.

這是從doesFileExist方法中截取的一段代碼,doesFileExist方法完成的主要功能是:這個方法會獲得一個字串陣列和一個檔案名.這個字元

串陣列存放的是從根目錄開始的一個路徑.doesFileExist方法中,如果檔存在,返回true,如果不存在,返回false;

既然知道了要做什麼事情,我們就很清楚的知道我們要去做什麼事情了:

首先,我們要先把字串陣列中的元素依次取出來,把它們連接到一起,形成一個完整的絕對路徑.然後,創建用這個路徑和已經得到的檔案名做

參加,生成一個File物件,利用File物件的exist()方法,來判斷這個檔是否存在.

那麼,我們的答案是什麼呢:
A:4
B:12
C:9
D:7

我也試著寫了一下測試類

import java.io.File;

public class Tester {
public static void main(String[] args) {
String[] directories = new String[] { "D:", "homework", "d0427" };
String filename = "table.xml";
System.out.println(doesFileExist(directories, filename));
}
public static boolean doesFileExist(String[] directories, String filename) {
String path = "";
for (String dir : directories) {
path = path + File.separator + dir;
}
File file = new File(path, filename);
return file.exists();
}
}

在我的電腦裏,D:\homework\d0427確實存在著一個檔table.xml,所以,返回值為true
本貼來自ZDNetChina中文社區 http://bbs.zdnet.com.cn ,本貼地址:http://bbs.zdnet.com.cn/viewthread.php?tid=384016

2009年2月2日 星期一

CSS 套用方式

我們可以用以下四種方式,將 CSS 套用入 HTML 文件中:

  • 行內套用 (Inline)
  • 嵌入套用 (Embed)
  • 外部連接套用 (External Link)
  • 匯入套用 (Import)

    行內套用


    我們可以在 HTML 文件內直接宣告樣式。舉例來說,


    <p style='font-family:verdana; font-size:16;'>This is font size 16.</p>



    以上的 HTML 文件在瀏覽器上會顯現為:

    This is font size 16.



    嵌入套用


    樣式可以嵌入於 HTML 文件中 (通常是在 <head> 內)。舉例來說,


    <head>
    <style type="text/css">
    div {
    background-color:#FF0000;
    }
    </style>
    </head>
    <body>
    <div>
    背景顏色是紅色
    </div>
    </body>



    以上的 HTML 會顯現出:

    背景顏色是紅色


    外部連接套用

    在這種方式下,所有的 CSS 樣式宣告都是存在另外一個檔案中。該檔案通常名稱為 .css。在 HTML 文件的 <header> .. </header> 之中,我們將用以下的程式碼將這個 .css 檔案連接進入:

    <link rel=stylesheet type="text/css" href="external-stylesheet.css">

    以上這一行會將在 external-stylesheet.css 這個檔案內所宣告的樣式加入 HTML 文件內。


    匯入套用

    外部的 CSS 樣式也可以被匯入進 HTML 文件。匯入的做法為利用 @import 這個指令。@import 的語法為:

    <STYLE TYPE="text/css">
    <!--
    @import url(http://www.mysite.com/style.css);
    -->
    </STYLE>

    @import 指令最初的用意,是為了能夠針對不同的瀏覽器而運用不同的樣式。不過,現在已經沒有這個必要。現在用 @import 的目的,最常是要加入多個 CSS 樣式。當多個 CSS 樣式被 @import 的方式加入,而不同 CSS 樣式互相有衝突時,後被加入的 CSS 樣式有優先的順位 (詳情請見 CSS 串接)。

  • 123

    CSS 語法

    以下內容來自於:

    http://css.1keydata.com/tw/syntax.php

    CSS 的全名為 Cascading Style Sheets,是一種樣式表 (Stylesheet) 語言。它的目的是為了對像 XHTML 及 HTML 之類的標記語言 (markup language) 提供一個顯示層。有了 CSS,我們就可以將資料層及顯示層分開:HTML 文件就只包括資料,而 CSS 則是告訴瀏覽器這些資料應該要如何顯現出來。

    宣告 CSS 樣式的語法如下:

    選擇器 {
    屬性:設定值;
    ...
    }


    在一個選擇器 (Selector) 中,可以設定的屬性數目沒有限制。

    選擇器主要有三種:型類 (Type) 選擇器、Class 選擇器、和 ID 選擇器。

    型類選擇器是 (X)HTML 標籤,如 <body> 和 <h1>。Class 和 ID 選擇器是使用者自訂的選擇器。我們會在之後討論這兩類的選擇器。

    樣式是以『屬性:設定值』的方式來制定。舉例來說,若我們要設定一個元素內的文字是黃色的,那就用以下的『屬性:設定值』:


    color:yellow;



    在以上的宣告內,color 是屬性,而 yellow 是設定值。

    在某些時候,一個屬性可能會有好幾個設定值。這些通常都是因為屬性是一個捷徑。舉例來說,margin 屬性可能會有 4 個設定值,而每一個值代表每一邊的邊界長度。

    Grouping


    如果有數個選擇器享有同樣的樣式,它們可以同時被宣告。這叫做 "grouping"。舉例來說,如果 <h1>, <h2>, and <h3> 都會有相同的樣式,那它們就可以用以下的方式被宣告:


    h1, h2, h3 {
    屬性:設定值;
    ...
    }



    後代選擇器 (Descendant Selectors)

    我們可以設定說,只有當甲元素在乙元素之內時,甲元素才會用某個樣式。若甲元素不在乙元素內的話,那甲元素就可以有其他的樣式。要達到這個目標,我們就要利用後代選擇器的方式。

    後代選擇器宣告的語法是:

    【父選擇器】【子選擇器】{
    屬性:設定值;
    ...
    }


    在以上的宣告中,只有當子選擇器是在父選擇器之內時,樣式才會被用到。這一類的語法可以包括好幾代的選擇器,而不是只有兩代而已。

    舉例來說,以下的宣告,


    li b {
    color:yellow;
    }



    代表在 <li> <b> 之內的文字是黃色的。不是在 <li> 之內的 <b> 中的文字,就不會套用黃色字體這個樣式。

    TEST1