Cd Chen's Services

ba ba ba la~~

Java 課程

OnlyOneInstance Example


class OnlyOneInstance {
    private String name;
    private static OnlyOneInstance instance = null;

private OnlyOneInstance() {

}

public String getName() {
return name;
}

public static OnlyOneInstance getInstance() {
if (instance == null) {
instance = new OnlyOneInstance();
instance.name = "This is the only one instance.";
}
return instance;
}
}

public class OnlyOneInstanceTest {

public static void main(String[] args) {
OnlyOneInstance instance = null;

// instance = new OnlyOneInstance();
instance = OnlyOneInstance.getInstance();
System.out.println(instance.getName());

OnlyOneInstance instance2 = OnlyOneInstance.getInstance();
System.out.println(instance2.getName());

System.out.println(instance == instance2);

}

}

Java 物件與字串判斷作業

請思考下列的程式,產生的結果為何??


public class TestString {

public static void main(String args[]) {
String str1 = "";
String str2 = "";
String str3 = new String();
Object obj1 = str3;

System.out.println("Q1: " + (str1 == str2));
System.out.println("Q2: " + (str2 == str3));
System.out.println("Q3: " + (obj1 == str3));
System.out.println("Q4: " + (str3.equals(str1)));
System.out.println("Q5: " + (str1.equals(obj1)));
}
}


身份證字號檢查程式

請寫一個 "身份證字號檢查程式",並檢查 A123647883 是否為正確的字號

身份證字號檢查演算法說明:
------------------------
第一位為英文字母
第二個數字是男女生之分,男生為 1,女生為 2

身份證字號後面八個數字之中,前面七個可以隨便打
最後一位為檢查碼,必須經過之前一個字母與 8 個數字的組合計算後得出

檢查碼的運算原則:

英文代號以下表轉換成數字
A=10 台北市 J=18 新竹縣 S=26 高雄縣
B=11 台中市 K=19 苗栗縣 T=27 屏東縣
C=12 基隆市 L=20 台中縣 U=28 花蓮縣
D=13 台南市 M=21 南投縣 V=29 台東縣
E=14 高雄市 N=22 彰化縣 W=32 金門縣
F=15 台北縣 O=35 新竹市 X=30 澎湖縣
G=16 宜蘭縣 P=23 雲林縣 Y=31 陽明山
H=17 桃園縣 Q=24 嘉義縣 Z=33 連江縣
I=34 嘉義市 R=25 台南縣

(1)英文轉成的數字, 個位數乘9再加上十位數
(2)各數字從右到左依次乘1、2、3、4....8

(1)與(2)的和,除10求出餘數
用10減該餘數,結果就是檢查碼,若餘數為0,檢查碼就是 0。

例如: 身分證號碼是 Z12345678?

Z 1 2 3 4 5 6 7 8 
    3 3
X X X X X X X X X X
1 9 8 7 6 5 4 3 2 1 
 ─────────────────────
3 + 27 + 8 + 14 + 18 + 20 + 20 + 18 +14 + 8 = 150
150/10=15....0 (餘數)
10-0=10 (檢查碼為0)
故,身份證字號為Z123456780

Java 作業:三角星星

請撰寫一個 Java 程式,執行後會顯示:


*
***
*****
*******
*********
*******
*****
***
*

的圖案

參考解答:



public class Star {

public static void main(String args[]) {
int j = 0;
for (int i = 0; i < 4; i++) {
String str = "*";
for (int k = 0; k < (i + j); k++) {
str += "*";
}
j++;
System.out.println(str);
}
for (int i = 4; i >= 0; i--) {
String str = "*";
for (int k = 0; k < (i + j); k++) {
str += "*";
}
j--;
System.out.println(str);
}
}
}

Java 作業:九九乘法表

請撰寫一個 Java 式,執行後在畫面上顯示
 1 * 1 = 1
 1 * 2 = 2
 1 * 3 = 3
 ...
 2 * 1 = 2
 ...
 9 * 8 = 72
 9 * 9 = 81

解答:

public class JavaApplication {

public static void main(String args[]) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
System.out.println( i + " * " + j + " = " + (i * j));
}
}
}
}


You are here