2014年2月18日 星期二

Learning the Java Language (1) : Language Basics


Variable 變量 變數



1. 有分大小寫
2. 字母,數字,下底線與$組合
3. 開頭(建議)為字母
4. 不允許空白
5. 不能為關鍵字(Keyword)或保留字(reserved word)

(建議)使用相關的字符,而非單字母表示
變量只有一個字詞則全小寫,多字詞則下個字首大寫
變亮為恆定植,多點變化(全大寫,以下底線組合)



Primitive Data Types 資料型態

byte
8-bit signed two's complement integer
-128~127
大量使用array時可替用以省空間

short
16-bit signed two's complement integer
-32768~32767
大量使用array時可替用以省空間

int
32-bit signed two's complement integer
-2^31~(2^31)-1
0~(2^32)-1
integer class的default單位
[額外的func : compareUnsigned, divideUnsigned ]

long
64-bit signed two's complement integer
-2^63~(2^63)-1
0~(2^64)-1
[int func也有額外提供long的使用]

float
single-precision 32-bit IEEE 754 floating point
大量使用array時可替用以省空間(相較於double)
[額外func : java.math.BigDecimal]

double
double-precision 64-bit IEEE 754 floating point

boolean
true and false one bit information

char
single 16-bit Unicode character
a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive)


Array 陣列

1.
int[ ] anArray;                           // 宣告,也可以用 int anArray[ ];
anArray = new int[10];            // 配置,用new新增一個物件

或是
int[ ] anArray = {
    100, 200, 300,
    400, 500, 600,
    700, 800, 900, 1000
};

2.
二維陣列
String[ ][ ] names = {
            {"Mr. ", "Mrs. ", "Ms. "},
            {"Smith", "Jones"}
        };
// Mr. Smith
System.out.println(names[0][0] + names[1][0]);
  
// Ms. Jones
System.out.println(names[0][2] + names[1][1]);

順序 : row major

3.
System.out.println(anArray.length);
印出長度
 
4.
System.arraycopy(A, i, B, j, n);
System.out.println(new String(B));
 
從A陣列的第i元素複製n個元素,到B陣列的第j元素起始貼
 
new String(?!)
 
5.
char[] B = java.util.Arrays.copyOfRange(A, 2, 9);
System.out.println(new String(copyTo));

java.util.Arrays.copyOfRange



Operator 運算子

Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

2.
int i = 5;
System.out.println(i);

System.out.println(++i); // prints 6

System.out.println(i++); // prints 6

System.out.println(i);   // prints 7
 
3.
?:與C一樣,是個if-then-else,true則是:的左邊return;flase則是右邊return
int value1 = 1;
int value2 = 2;
int result;
boolean someCondition = true;
result = someCondition ? value1 : value2;

System.out.println(result);
// output "1"
 
4.
bitwise and[&] / or[|] / exclusive or[^]
(以bit為單位的and / or / exclusive or) 
perform bitwise and bit shift[>> <<] operations on integral types
(以int type來表示)

int bitmask = 0x000F;
int val = 0x2222;
        
System.out.println(val & bitmask); 
// prints "2"



Control flow statement 條件判斷式

1.
if-else
if-else if-else

2.
switch

int month = 8;
String monthString;
switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
 
                     ︴
 
      default: monthString = "Invalid month";
                     break;

3.
閏年 
int month = 2;
int year = 2000;
int numDays = 0;

switch (month) {
        case 1: case 3: case 5:
        case 7: case 8: case 10:
        case 12:
            numDays = 31;
            break;
        case 4: case 6:
        case 9: case 11:
            numDays = 30;
            break;
        case 2:
            if (((year % 4 == 0) && 
                !(year % 100 == 0))
                || (year % 400 == 0)) 
                // 閏年條件式:O
                numDays = 29;
            else
                numDays = 28;
            break;
        default:
            System.out.println("Invalid month.");
            break;
}
System.out.println("Number of Days = " + numDays);

4.
while (true){
    // your code goes here
}
do {
     statement(s)
} while (expression); 

do-while會停止在最後狀態,不會多做一次

5.
for (i = 0; i < arrayOfInts.length; i++) {
       if (arrayOfInts[i] == searchfor) {
            foundIt = true;
            break;
       }
}
跳出當前的state,範例中就是for

或是用BreakWithLabel的方式...
public static void main(String[] args) {

        int[][] arrayOfInts = { 
            { 32, 87, 3, 589 },
            { 12, 1076, 2000, 8 },
            { 622, 127, 77, 955 }
        };
        int searchfor = 12;

        int i;
        int j = 0;
        boolean foundIt = false;

    search:
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length;
                 j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search;
                }
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor + " at " + i + ", " + j);
        } else {
            System.out.println(searchfor + " not in the array");
        }
 
利用label跳出當前的狀態,注意這邊for兩圈都跳出


6.
for (int i = 0; i < max; i++) {
        // interested only in p's
        if (searchMe.charAt(i) != 'p')
            continue;

        // process p's
        numPs++;
}
 
continue略過loop中後段的程式,進入下一次的loop描述
因次只有符合條件式,才會計算continue後的程式


7.
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;

int max = searchMe.length() - substring.length();

test:
    for (int i = 0; i <= max; i++) {
        int n = substring.length();
        int j = i;
        int k = 0; //每次更新index會歸零
        while (n-- != 0) {
            if (searchMe.charAt(j++) != substring.charAt(k++)) {
                continue test;
            }
        }
        foundIt = true;
            break test;
    }
System.out.println(foundIt ? "Found it" : "Didn't find it");



沒有留言:

張貼留言