# java 教學 # Java 教學 ## VAR 在 Java 中,變數(Variable)提供一個有名稱的記憶體儲存空間,簡單來說就是一個可以存放值的空間。變數可包含的資訊包括變數資料型態(Type)、變數記憶體位址和變數儲存值。Java 使用 `int`、`float`、`double`、`String` 等來宣告變數名稱和型態。 ```java int a = 0; int b; String str; String user = "111"; String mo = "222"; ``` * question ```java public static void main(String[] args) { String a = "12"; String b = "552233"; String c = a + b; System.out.print(c); } ``` ## 邏輯運算子 <h3>邏輯運算子</h3> 常用的邏輯運算子有四種,AND,OR,NOT,XOR,全部皆用 **binary** 型態運算 * AND(&) | A | 1 | 1 | 0 | 0 | | ------ | --- | --- | --- | --- | | B | 0 | 1 | 1 | 0 | | Output | 0 | 1 | 0 | 0 | * OR(|) | A | 1 | 1 | 0 | 0 | | ------ | --- | --- | --- | --- | | B | 0 | 1 | 1 | 0 | | Output | 1 | 1 | 1 | 0 | * NOT(^) | A | 1 | 1 | 0 | 0 | | ------ | --- | --- | --- | --- | | B | 0 | 1 | 1 | 0 | | Output | 0 | 1 | 0 | 1 | * XOR(~) | A | 1 | 1 | 0 | 0 | | ------ | --- | --- | --- | --- | | B | 0 | 1 | 1 | 0 | | Output | 1 | 0 | 1 | 0 | ```java int x = 10; // 二進制表示為 1010 int y = 3; // 二進制表示為 0011 int andResult = x & y; int orResult = x | y; int xorResult = x ^ y; int notResult = ~x; ``` ![Intro.jpg](https://hackmd.io/_uploads/rJy-iJIX6.jpg) ## math function math function是java中用於解決各種數學問題的函式庫 Math函數可以用於兩個地方 > 直接於輸出端使用 > 修改變數 **目前作業用過的函數包含下列兩種:Math.random、Math.floor** | Method | usage | 預設輸出格式 | | | | | ---------------------------------------- | ---------------------------------- | ------------ | --- | --- | --- | | Math.floor(x)\Math.ceil(x)\Math.round(x) | 計算無條件捨去\進位\四捨五入的結果 | double | | | | | Math.random | 在一定範圍中自動產生亂數 | double | | | | Math.sqrt(x) | 找出x的平方根(x^1/2) | double | | | | | Math.pow(x,y) | 找出x^y的數值 | long | | | | | Math.sin(x)\cos(x)\tan(x) | 找出sin\cos\tan(x)radian 的數值 | double | | | | | Math.toRadians(X)\toDegrees(x) | 將角度\弧度量互相轉換 | double | | | | | Math.exp(x) | 計算e^x | double | | | | | Math.log(x) | 計算某數以10為底的log值 | double | * **tips** 如果對輸出的method預設的型態不滿意\認為需要修改,可以在Math函數前方加上一個(型態)用於修改,在不會導致執行錯誤的前提下,會以開發者指定的型態輸出 >> 括號內填入要指定輸出的型態,以下是一個例子 ```java int run =(int) Math.floor(res * 1000000.0) / 1000000.0; ``` <h3> 範例程式</h3> * Math.floor(x)\Math.ceil(x)\Math.round(x) ```java double x = 7.1234567890; double floorResult = Math.floor(x); // 結果為 7.0 double ceilResult = Math.ceil(x); // 結果為 8.0 long roundResult = Math.round(x); // 結果為 8 double example = Math.ceil(x*10000)/10000; //結果為7.1235 ``` * Math.random: ```java double randomValue = Math.random(); // 返回一個 0 到 1 之間的亂數值 int randomIntInRange = (int)(Math.random() * 100); // 返回 0 到 99 之間的整數亂數 ``` * Math.pow(x, y): ```java double x = 2.0; double y = 3.0; double powResult = Math.pow(x, y); // 結果為 8.0 (2^3) ``` * Math.sin(x), Math.cos(x), Math.tan(x): ```java double x = Math.PI / 6; // 30 度轉換為弧度 double sinResult = Math.sin(x); // 返回 sin(30°) 的值 double cosResult = Math.cos(x); // 返回 cos(30°) 的值 double tanResult = Math.tan(x); // 返回 tan(30°) 的值 ``` * Math.toRadians(x), Math.toDegrees(x): ```java double degrees = 45.0; double radians = Math.toRadians(degrees); // 將 45 度轉換為弧度 double degreesConverted = Math.toDegrees(Math.PI / 4); // 將 π/4 弧度轉換為角度,應該為 45.0 度 ``` * Math.sqrt(x): ```java double x = 25.0; double sqrtResult = Math.sqrt(x); // 結果為 5.0 ``` * Math.exp(x): ```java! double x = 2.0; double expResult = Math.exp(x); // 結果為 e^2 ``` * Math.log(x): ```java! double x = 100.0; double logResult = Math.log(x); // 以 10 為底的 log(100) 結果 ``` ## for loop for loop 適用於處理有次序的情況,例如把資料輸入進陣列中 以下是for loop的語法簡介 ```java for (A;B;C;){ D; } ``` 這裡是每個部分的詳細說明: A:初始化區塊,這個部分通常用於設定迴圈的計數器或初始化變數。這是在迴圈開始之前執行的程式碼 B:條件式,這個部分定義了迴圈的繼續條件。只有當條件為真時,迴圈才會繼續執行。如果條件為假,迴圈將結束 C:迭代區塊,這個部分通常包含遞增或遞減計數器的程式碼 這些程式碼在每次迭代之後執行,通常用於更新計數器的值 D:迴圈主體,這是在每次迭代中執行的程式碼區塊。這是重複執行的主要程式碼 迴圈的執行流程如下: 執行 A 初始化區塊 檢查 B 條件式如果條件為假,迴圈結束,否則執行下一步 執行 D 迴圈主體 執行 C 迭代區塊,通常用於更新計數器的值 回到步驟2,重複檢查條件和執行主體,直到條件為假 <h3>範例程式</h3> ```java int a=0; int b=10; int c=0; for(a=0;a<b;a++){ c= a*b; System.out.print(c+","); } ``` * output ```java! 0,10,20,30,40,50,60,70,80,90 ``` * question ```java!= package courseExample; import java.util.Scanner; public class courseExample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int i=0; for( i = 0; i<a;i++){ System.out.print(i +","); } System.out.println(i); } } ``` 假設 imput a = 20 請問最後會有幾項輸出?(輸出一次即為一項輸出) 輸出為何? ~when your code is a mess but it somehow works~ ![EQ6AbNQUUAEPkLT.jpg](https://hackmd.io/_uploads/S1rHo1U76.jpg) ## if-else statement if-else statement是一種判斷式,當特定的條件被滿足時,就會觸發設定好的程式碼 當判斷式中任意條件得到滿足時,就會執行滿足該條件狀況下的code,如果不滿足則跳過該code,繼續向下執行,直到遇到滿足條件的code為止 ### 範例程式 ```java!= if(條件式1){ 當條件1被滿足、觸發時會執行的code } else if(條件式2){ 當條件2被滿足、觸發時會執行的code } else if(條件式3){ 當條件3被滿足、觸發時會執行的code }//請注意,條件式可以無限制增加,但整個if/else僅有一個條件式會被執行 else { 當上述條件皆無法被滿足時會執行的code } #範例一 int a= 0; if (a==0){ System.out.println("a ="+a); } ``` ```java!= #範例二 package courseExample2; import java.util.Scanner; public class courseExample2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int i=0; if(a==i){ System.out.println(a); } else if(a<i){ system.out.println("hihi"); } else{ System.out.println("error"); } } } ``` * question ```java int x = 10; if (x > 5) { System.out.println("x is greater than 5"); } else if (x > 8) { System.out.println("x is greater than 8"); } else { System.out.println("x is something else"); } ``` 請問上述code的輸出是什麼? **** **予告 前方內容爆多,但很重要,自己決定要不要看** **予告 前方內容爆多,但很重要,自己決定要不要看** **予告 前方內容爆多,但很重要,自己決定要不要看** ## array * Why we need array? 回到作業三,三個數字用if-else statement排序會長得像這樣 ```java!= public class S1261017_HW3_A { public static void main(String[] args) { System.out.println("Please enter three numbers"); Scanner in=new Scanner(System.in); int a=in.nextInt(); int b=in.nextInt(); int c=in.nextInt(); if ((a>b)&&(b>c)) {System.out.println(c+" "+b+" "+a);} else if((b>a)&&(a>c)) {System.out.println(c+" "+a+" "+b);} else if ((c>a)&&(a>b)) {System.out.println(b+" "+a+" "+c);} else if ((c>b)&&(b>a)) {System.out.println(a+" "+b+" "+c);} else if ((b>c)&&(c>a)) {System.out.println(a+" "+c+" "+b);} else if ((a>c)&&(c>b)) {System.out.println(b+" "+c+" "+a);} } } ``` 那....如果10個數字呢?會不會打到亂掉?(gpt範例在[附錄](/v8b4BbTlSgCg1O2jywifsA),有興趣自己讀看看 所以,利用同類項合併,將功能、型別(type)類似的變數整合在一起的陣列(array)就是這時候最好的選擇(但未來學linked list、vector後就不一定了,但礙於難度因素,就先不教了) * 陣列用法 宣告方式: type[] = new type [length]; type[] = new type [] = {要儲存的資料}; ### 範例程式-宣告 ```java!= int[]example1 = new int [10]; int[]example2 = {1,2,3,4,5,6,7,8} ``` * 陣列的索引值(index) 陣列是直接在記憶體中切分出一段連續的記憶體,用於儲存資料的方式,因此其中各元素皆會有一個索引值(index),索引值會從0開始到陣列元素總量-1 * 陣列歸零 雖然說不常發生,但為了以防萬一,在使用沒有預先輸入數值(如上面的example1)時,**一定要先將所有數值歸零**,不然陣列中有可能會被預先塞進一些奇怪的數值,造成overflow/memory error 這些令人不悅的結果 * 歸零的方法 用for loop將陣列中的所有數值先設定為0 ### 範例程式-歸零 ```java!= int []example3 =new int [20000]; for(int i=0;i<20000;i++){ example[i]=0; } ``` * 陣列輸入/出資料 陣列(array)輸入/出資料的方式有兩種,其一是用跟一般變數(variable)一樣的方法輸入/出,此方法常用於儲存無規律的資料 ```java!= int []example4 =new int [3]; example4[0]=2222; example4[2]=234; System.out.println(example4[0]); ``` 另一種方式則是利用for loop輸入/出資料,常用於儲存能找到規律的資料,或是將整個陣列輸出 ```java!= int []example5 = new int[20]; int []example6 = new int[20]; for(int i=0;i<20;i++){ example5[i]=sc.nextInt(); example6[i]=(int)(Math.random() * 900); } for(int j=0;j<20;j++){ System.out.println(example6[i]); } ``` * tips 由於陣列是一個具有固定大小的資料型態,陣列的長度用變數賦予(如下面的code),是一種不安全的作法,在特定條件下也有可能會被編譯器以安全性問題檔下來,無法編譯,因此,盡可能不要這麼做(以後會學到可以這麼用且類似陣列的資料型態) ```java!= int i=9999; int []example5 = new int[i]; ``` 那不知道有多少變數要輸入要怎麼辦?(常見於不清楚作業/考試的測試資料有多少) 當然是 **給爆陣列長度**,保證資料量不會超出陣列大小 例如這樣(但要記得,輸入輸出資料、歸零陣列時,請用double) ```java!= int []example9 = new int[999999999]; for(double i=0;i<999999999;i++){ example9[i]=0; } ``` * question 觀察下方的code,請問最後的輸出值為何 ```java!= int []que1= new int [200]; for (int i=0;i<200;i++){ que1[i]=0; } //這段的作用等等再說 for (int j=0;j<200;j++){ que1[j]=j; } System.out.println(que[199]); ``` ## 期中加油,練習題有空再放 ## 接下來不要理我,不會考(但很好用) ## ArrayList Arraylist是Array的一種變異體,屬於Dynamic Array,跟一般的Array 差別在於Array在compile當下就會決定好總長,不能變更,ArrayList可以imput、output、deleate. * **import** ```java!= import java.util.ArrayList ``` * **宣告** ```java!= ArrayList<type>name = new ArrayList<type>(length); ``` * **type** * 不能用origin喔 | origin | in arraylist | | -------- | -------- | | byte | Byte | | boolean | Boolean | short |Short int| Integer long| Long float| Float double| Double char |Character * **新增元素** ```java!= name.add(data) ``` * **移除元素** ```java!= name.remove(index); ``` * index為索引值