iT邦幫忙

2026 iThome 鐵人賽

DAY 14
0

本日練習:

  1. 試撰寫 int cubic(int x) 函數,可傳回引數 x 的三次方
import java.util.Scanner;
public class CH14_1 {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        System.out.println(cubic(x));
        sc.close();
    }
    public static int cubic(int x){
        return x * x * x;
    }
}
  1. 試撰寫一函數 int product(int[] arr),可傳回一維陣列的最大值與最小值的乘積,若 arr = {7,3,2,4,5},則回傳 14
public class CH14_2 {
    public static void main(String[] args){
        int[] arr = {15,50,65,38,94,25,79,44,19,89,54,73};
        System.out.println(product(arr));
    }
    public static int product(int[] arr){
        int max = arr[0];
        int min = arr[0];
        for(int i = 1; i < arr.length; i++){
            if(arr[i] > max)
                max = arr[i];
            if(arr[i] < min)
                min = arr[i];
        }
        return max * min;
    }
}

本日學習:

  1. 使用類別來設計完整程式:
class Rectangle{
    int width, height; // 定義 Rectangle 的類別
}
public class CH14_3 {
    public static void main(String[] args){
        Rectangle r1;
        r1 = new Rectangle(); // 建立新物件
        r1.width = 10;
        r1.height = 20;
        System.out.println("width = " + r1.width);
        System.out.println("height = " + r1.height);
    }
}
  1. 類別先寫後寫不影響
  2. 可同時建立多個物件
  3. 定義函數成員時,要有 return
  4. 呼叫函數成員:物件名稱.函數名稱(型別 引數1, 型別 引數2, ......)
  5. try:定義一個圓形類別 Circle,它有 radius、pi 兩個資料成員,和一個 area 函數成員
class Circle{
    double radius;
    double pi = 3.14;
    double area(){
        return radius * radius * pi;
    }
}
public class CH14_4 {
    public static void main(String[] args){
        Circle c1;
        c1 = new Circle();
        c1.radius = 5;
        System.out.println("圓形面積 = " + c1.area());
    }
}
  1. 如果建立兩個物件,這兩個物件的資料成員會被配置於不同記憶體區塊內,也就是說即使不小心更動其中一個物件的數值,另一個也不會受影響
  2. 如果在類別宣告的內部使用資料成員,不須加上呼叫它的物件名稱
    • 撰寫定義時還不會知道誰要呼叫
    • radius 就直接 radius,不用 c1.radius
    • 或是 this.radius 也可,表示取用此一資料成員的物件
  3. 在類別宣告的外部使用資料成員時,就一定需要指明是哪一個物件要用
  4. 若是在類別內呼叫其他函數成員:可以成功,不須透過物件(或是一樣透過 this)

上一篇
Day 13:類別(1)
下一篇
Day 15:類別(3)
系列文
從零開始學程式語言:Java 新手修煉記 共 17 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言