jake
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Java筆記 # java ### 小技巧 difference between float and double ```java float var1 = 123; float var2= 12.3f; //系統default 有小數點的數為double,故要寫為12.3f double var3 = 123; double var4 = 12.3; 亂數產生 ex1:生成0~100的亂數 --- //亂數產生0-100的整數成績,範圍中有101個值 score = (int)(Math.random()*101); ex2:生成0~100的亂數 //大樂透,1-49,範圍中有49個值 ```clike= score = (int)(Math.random()*49)+1; for loop的兩種寫法 int [] b = new int[] {1,2,3,4}; //一般 for loop,要跑幾圈可以自由定義 for (int i=0;i<b.length;i++) System.out.print(b[i]+" "); //for-each,必須跑完array中的所有元素,較為死板 for (int v:b) System.out.print(v+" "); input nner[clore](/) 完整範例 Scanner需要import如下: comment >this is comment [clore](/) >import java.util.Scanner; 格式如下:[HackMD 使用教學](/fNYeUVJNQr6G6ZA5nwn9oA) ```clike= int a, b; Scanner sc = new Scanner(System.in); //System.in是 System.out.print("a= "); a = sc.nextInt(); //讀取下個輸入 System.out.print("b= "); b = sc.nextInt(); ... sc.close(); 物件導向 封裝(Encapsulation) 封裝的概念說明: 存取修飾字(access level modifier) within class within package outside package by subclass only outside package public √ √ √ √ protected √ √ √ X default √ √ X X private √ X X X 如下舉例,建立一個名為Bike的class: public class Bike { protected double speed; public void upSpeed() { speed= speed <1 ? 1:speed*1.2; } public void downSpeed() { speed =speed>1 ? 0 :speed*0.7; } public double getSpeed() { return speed; } } 另新增一個名為Scooter 的class,並且繼承Bike的 public class Scooter extends Bike{ public void upSpeed() { speed = speed <1?1:speed*1.8; } } 因此在main中,可導入上述兩個class: import tw.org.iii.myclasses.Bike; import tw.org.iii.myclasses.Scooter; public class ZY20 { public static void main(String[] args) { Bike myBike = new Bike(); Bike urBike = new Bike(); System.out.println(myBike.getSpeed()); System.out.println(urBike.getSpeed()); System.out.println("---"); Scooter s1 = new Scooter(); s1.upSpeed();s1.upSpeed();s1.upSpeed(); s1.downSpeed(); System.out.println(s1.getSpeed()); } } overload and override oveload public class Bike { //has-a member (屬性, 方法) //has-a speed, upSpeed(), downSpeed(), getSpeed() // protected double speed; public void upSpeed() { speed= speed <1 ? 1:speed*1.2; } @Overload //由於參數不同,所以可寫不同function public void upSpeed(boolean isUphill) { if(isUphill) { speed =speed>1 ? 0 :speed*1.1; }else { speed =speed>1 ? 0 :speed*1.4; } } } override public class Scooter extends Bike{ private int gear; public int getGear() {return gear;} public void setGear(int gear) { //this是指向本類別 if(gear>=0 && gear <=5) { if(Math.abs(gear-this.gear)==1) { this.gear = gear; } } } @Override public void upSpeed() { if (gear>0) {speed = speed <1?1:speed*2;} } } 需要注意的是,override父類別的方法權限,只能擴大不能縮小 建構子(Constructor) 當new一個物件實體時,constructor會將物件實體其進行初始化。 所有類別皆有建構子,建構子的第一道敘述,包含所有父類別的建構子,其就算沒有寫建構子也會執行super() 在沒有撰寫任何建構式時,編譯器會自動加入無參數預設建構式(Default constructor) 如果自行定義了建構式,就不會自動加入任何建構式了。 ex: 在main中執行Other,Other與父類的建構子皆會執行 class Some { Some(){ //這行會在背景執行,就算沒有Constructor也會執行 //super();//這裡執行的是Object的Constructor System.out.println("Call Some()"); } Some(int i){ System.out.println(String.format("Call Some(%d)", i)); } } class Other extends Some{ Other() { //這裡也有,但因為執行父類的其他建構式所以super()不執行 //super(); super(10); System.out.println("Call Other()"); } } public class ZYTest { public static void main(String[] args) { Other o1 = new Other(); } } 其output為: Call Some(10) Call Other() 介面與多型 abstract public class ZY33 { public static void main(String[] args) { // Brad331 obj1 = new Brad331();// 由於有abstract 所以無法建立obj Brad331 obj2 = new Brad332(); obj2.m1(); obj2.m2(); System.out.println("分隔線---"); //也可以直接定義,如下: Brad331 obj1 = new Brad331() { void m2() {System.out.println("m2()");} }; obj1.m2(); } } abstract class Brad331{ void m1() {System.out.println("Brad331:m1()");} abstract void m2(); //抽象方法,沒有定義的方法實作。若有抽象方法,則也必須是定義抽象class //目的: 強迫subclass創造多型 } //多型 class Brad332 extends Brad331{ void m1() {System.out.println("Brad332:m1()");} void m2() {System.out.println("Brad332:m2()");} 其output為: Brad332:m1() Brad332:m2() 分隔線— m2() interface public class ZY35_interface { public static void main(String[] args) { Circle c1 = new Circle(3); } static double sumArea(Shape s1,Shape s2) { return s1.getArea()+s2.getArea(); } } // interface 定義介面=>定義規格 //interface 中的方法皆為抽象方法 interface Shape { double getLength(); double getArea(); } class Circle implements Shape { double r; Circle(double r){ this.r = r; } public double getLength() { return 2*Math.PI*r; } public double getArea() { return Math.PI*Math.pow(r, 2); } } String vs StringBuilder vs StringBuffer ``` 三者比較 ```java= ```click= //String String salute = "Hi " + " my " + "name " + " is ; //StringBuffer or StringBuilder StringBuffer salute = new StringBuffer("Hi ").append(" my ").append.(" name ").append(" is "); StringBuilder salute = new StringBuilder("Hi ").append(" my ").append.(" name ").append(" is "); 物件特性 Exception 異常 try & catch 若要將run time error當作例外案例處理的話,則可以使用try把預期出現error的程式碼包起來。並用catch來抓取不同類型的exception,如下則有用ArithmeticException及ArrayIndexOutOfBoundsException兩種。 public static void main(String[] args) { // Exception 例外, 異常 int a = 10, b = 3; int c; System.out.println("Start"); try { / c = a / b; System.out.println(c); int[] d = {1,2,3}; System.out.println(d[0]); System.out.println(d[2]); }catch (ArithmeticException e) { System.out.println("XX:" + e.getLocalizedMessage()); }catch(ArrayIndexOutOfBoundsException ae) { System.out.println("Ooop!"); } System.out.println("Game Over"); } } throws 寫class的時候,為了保留彈性給使用者,可用throws。而使用者就一定要處理Exception的部分。 public class ZY38 { public static void main(String[] args) { Bird b1= new Bird(); try { b1.setLeg(2); } catch (Exception e) { System.out.println("....."); } } } class Bird { private int leg; void setLeg(int leg) throws Exception { if (leg >=0 && leg <=2) { this.leg = leg; }else { throw new Exception(); } } } IO file api ``` ```click= 新建檔案 import java.io.File; public class ZY39_IO { public static void main(String[] args) { File f1 = new File("dir2/dir3/dir4/dir5/dir6"); //File f1 = new File(在此寫path & file) if (f1.exists()) { System.out.println("ok:"+f1.getAbsolutePath()); }else { System.out.println("not exists"); if (f1.mkdirs()) { System.out.println("create success"); }else { System.out.println("create failure"); } } } } 輸出資料 byte by byte的輸出(FileOutputStream) 不同編碼的寫入 import java.io.FileOutputStream; import java.io.IOException; public class ZY40_ioStream { public static void main(String[] args) { //Unix \n; Windows \r\n String data = "資策會Hello wor中壢ld\n1234567\n7654321\ngood!!!"; try { FileOutputStream fout = new FileOutputStream("dir1/file1.txt",false); //這裡的True/False可選擇append or rewrite fout.write(data.getBytes()); fout.flush(); fout.close(); System.out.println("ok"); }catch(IOException e) { e.printStackTrace(); } System.out.println("end"); } } 若是將catch FileNotFoundException放到catch IOException後面出現錯誤,FileNotFoundException是沒有辦法被捕捉到的,因為FileNotFoundException是IOException的子類別 java.io.FileNotFoundException的繼承 java.lang.Object java.lang.Throwable java.lang.Exception java.io.IOException java.io.FileNotFoundException 整段寫入(FileWriter) import java.io.FileWriter; public class ZY43_fileWriter { public static void main(String[] args) { try { FileWriter writer = new FileWriter("dir1/file2.txt"); writer.write("Hello, 中壢資策會"); writer.flush(); writer.close(); System.out.println("ok"); }catch(Exception e) { e.printStackTrace(); } } } flush(): From the docs of the flush method: Flushes the output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination. The buffering is mainly done to improve the I/O performance. More on this can be read from this article: Tuning Java I/O Performance. 輸入資料 byte by byte的讀取: import java.io.FileInputStream; public class ZY41_ioStream_input { public static void main(String[] args) { try { FileInputStream fin = new FileInputStream("dir1/file1.txt"); int c; //寫法1: while ((c = fin.read())!=-1) { System.out.print((char)c); } //寫法2: // while (fin.available()>0) { // c = fin.read(); // System.out.print((char)c); // } fin.close(); System.out.println("ok"); }catch(Exception e) { e.getLocalizedMessage(); } } } line by line的讀取 (讀取.cvs file) import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; public class ZY44 { public static void main(String[] args) { try { //opening connection to an actual file // FileInputStream fin = new FileInputStream("dir1/maskdata.csv"); // //input -> reader, 並且可以選擇不同的編碼格式 // InputStreamReader isr = new InputStreamReader(fin,Charset.forName("UTF-8")); // //建立buffer存取 // BufferedReader reader = new BufferedReader(isr); BufferedReader reader = new BufferedReader(new InputStreamReader (new FileInputStream("dir1/maskdata.csv"), Charset.forName("UTF-8"))); String Line; int num = 1; while((Line = reader.readLine())!=null) { //System.out.println(num++ +":"+Line); String[] row = Line.split(","); if (row[2].contains("中壢")) { System.out.println(row[1]+":"+row[2]+":"+row[4]); } } reader.close(); }catch(Exception e) { e.getLocalizedMessage(); } } } URL IO 資料結構 Collection set 不會重複 沒有順序 TreeSet List 可重複 有序,與加入有關 ArrayList LinkedList 有pop & poll(FIFO & FILO的概念) 選擇 Repo

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully