今天幫學姐打java作業,碰了將近兩年沒用的Java
也花了我大概半小時的時間做複習0.0
覺得太久了,所以來打一篇大全XDDD
1. Class 基本結構(對你沒看錯我連class結構都忘了zz)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| // 如何new一個classReader reader = new Reader(1, 2);public class Reader { //class名稱,通常是名詞 int a; int b; public Reader(int a, int b) { //建構子 this.a = a; this.b = b; } public int add() { //定義function,這個class有什麼功能 return (a+b); } // 如果有main() public static void main(String[] args) { System.out.println("HI"); }} |
2. 讀取txt檔
1
2
3
4
5
6
7
8
| //try (BufferedReader br = new BufferedReader(new FileReader("讀取檔案路徑.txt"))) { String line; while ((line = br.readLine()) != null) { //一行一行讀取 //你要對這一行做的事 }} |
3. 輸出txt檔
1
2
3
4
5
6
7
8
9
10
11
12
13
| try{ fw = new FileWriter("你要寫的檔名路徑.txt", true); bw = new BufferedWriter(fw); bw.write("你要寫進去的東西\n");} catch(IOException e){} finally{ try{ bw.close(); } catch(IOException e){}} |
4. 讀取鍵盤輸入
1
2
| Scanner scanner = new Scanner(System.in);int x = scanner.nextInt(); |
5. HashMap遍歷與排序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| /* 遍歷map */Iterator it = myMap.entrySet().iterator();while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); // 這裡擺要做的事 // key = pair.getKey(); // value = pair.getValue(); it.remove(); // avoids a ConcurrentModificationException} /* 排序Map:利用treeMap */
public Map sortByKey(HashMap<String, Integer> map){
Map<String, Integer> treeMap = new TreeMap<String, Integer>(myMap);treeMap = builder.sortByKey(myMap); //已排序好 |
5. 其他
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| // Integer -> int -> doubleint tmp = (int)a();double db = new Double(tmp);// HashMap簡單使用HashMap< String, Integer> map = new HashMap< String, Integer>();map.put("One", 1);int value = map.get("One");//字串比較int equal = string1.equals(string2);// String -> Integer/DoubleInteger i = Integer.valueOf("12345");Double d = Double.valueOf("1.1");// 數學Math.pow(4, 5); //4的5次方Math.sqrt(144); //144開根號(double)Math.log10((double)1000.0); //log10 |