# 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
{"metaMigratedAt":"2023-06-16T03:34:31.127Z","metaMigratedFrom":"Content","title":"Java筆記","breaks":true,"contributors":"[{\"id\":\"e2da14d7-1e89-4ae7-8139-a0da5f5f98dc\",\"add\":10058,\"del\":112}]"}