此份筆記適合:已經會 C++ 但想開始學 Java 的人。
IDE
IntelliJ IDEA Community Edition
學習資源
架構
public class Main {
public static void main(String[] args) {
...
}
}輸入
import java.util.Scanner;Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();輸出
System.out.println("Hello World"); //換行
System.out.print("Hello World"); //不換行String
判斷兩字串是否相同,不能使用 ==,而是使用 equals()。
String s = "Andy";
System.out.println(s.equals("Sandy"));concat():將兩字串合併
concat = concatenate (v.) 連接
String s1 = "Hello ";
String s2 = "World";
System.out.println(s1.concat(s2)); //Hello WorldArray
int[] arr = {1, 2, 3, 4, 5};
int[] arr = new int[5];ArrayList
有如 C++ 的 vector。
import java.util.ArrayList;ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(10);
arr.add(20);
arr.add(30);
arr.set(2, 87); //set index 2 to 87
arr.remove(0); //remove index 0
arr.remove(Integer.valueOf(20));
System.out.println(arr); //87二維陣列
int[][] arr = {{1,2,3},{4,5,6},{7,8,9}};
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}例外處理 (Exception Handling)
try {
//檢查此區塊程式是否有例外
} catch (例外類型 ex) {
//處理例外
} finally {
//可有可無,無論是否有例外都會執行
}ArithmeticException (數學運算例外)
try {
System.out.println(5 / 0);
} catch (ArithmeticException ex) {
System.out.println(ex.getMessage()); // / by zero
}ArrayIndexOutOfBoundsException (陣列索引值例外)
try {
int[] arr = new int[5];
arr[5] = 2;
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println(ex.getMessage()); //Index 5 out of bounds for length 5
}