#27163: Java熟練物件導向


910077@gm.yhsh.tn.edu.tw (歐宗穎)


A. 這是最直觀的解法(Scanner):

import java.util.Scanner;

public class Java{

public static void main(String[] args){

Scanner sc = new Scanner(System.in);

System.out.println("hello, "+sc.nextLine());

}

}

 

B. 這是善用物件導向的做法:

public class Java{

public static void main(String[] args){

System.out.println("hello, "+new java.util.Scanner(System.in).nextLine());

// 你會發現一件事:如果我這個API使用次數只有一次,用這種方法會比上面那隻程式碼要簡潔得多

}

}

 

C. 這是鑽漏洞讓記憶體耗用0kb的做法(BufferedReader):

import java.io.BufferedReader;

public class Java{

public static void main(String[] args)throws java.io.IOException{

try(BufferedReader reader = new BufferedReader(new java.io.InputStreamReader(System.in))){

// 我在這裡用try嘗試自動關閉資源,可加可不加

System.out.println("hello, "+reader.readLine());

}

}

}

#27280: Re:Java熟練物件導向


tonysu1204@gmail.com (東毅中)


可不可熟成物件導向