Thuta Learning
Java
ProjectsProgrammingအခြေခံ

Student Manager Project - Part 3: Exceptions & Final Report

Javaသင်ခန်းစာ 3440 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Exception ကို extend လုပ်ပြီး InvalidScoreException နဲ့ StudentNotFoundException ကို ရေးနိုင်ဖို့
  • throws clause က method contract ဖြစ်ပြီး caller ကို handle လုပ်ခိုင်းတာကို ရှင်းပြနိုင်ဖို့
  • Line တစ်ကြောင်းချင်းစီမှာ try-catch ထားပြီး မှားတဲ့ line တစ်ကြောင်းကြောင့် batch တစ်ခုလုံး မရပ်အောင် လုပ်နိုင်ဖို့
  • Comparator.comparingDouble(...).reversed().thenComparing(...) နဲ့ copy တစ်ခုကို စီပြီး printf table ထုတ်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

စာမေးပွဲပြီးတော့ ဆရာတွေက အမှတ်စာရွက် တစ်ထပ်ကြီးကို ရုံးကို ပို့ပါတယ်။ စာရွက်အများစုက မှန်ပေမယ့် တချို့မှာ "120" လို မဖြစ်နိုင်တဲ့ အမှတ်၊ မရှိတဲ့ ကျောင်းသားနံပါတ်၊ ဖတ်လို့မရတဲ့ လက်ရေး ပါလာပါတယ်။ စာရေးမက စာရွက်တစ်ရွက် မှားတာနဲ့ တစ်ထပ်လုံးကို ပစ်ပြီး အိမ်ပြန်သွားရင် မကောင်းပါဘူး။ မှားတဲ့ စာရွက်ကို ဘေးဖယ်ပြီး "ဘာကြောင့် ပြန်ပို့တယ်" ဆိုတာ မှတ်စု ရေး၊ ကျန်တာကို ဆက်သွင်းရပါမယ်။

Java မှာ အဲဒီ "ဘေးဖယ်ပြီး မှတ်စုရေးတာ" က exception ပစ်ပြီး catch လုပ်တာပါ။ Part 3 က ဒီ mechanism ကို ထည့်ပြီး နောက်ဆုံးမှာ အမှတ်အမြင့်ဆုံးကနေ စီထားတဲ့ report ကို ထုတ်ပါတယ်။

Problem → Why → Solution

ပြဿနာ: မှားတဲ့ line တစ်ကြောင်းက ကျန်တဲ့ line တွေကို ဖျက်ပစ်တယ်

ပထမ draft က for loop တစ်ခုလုံးကို try block တစ်ခုတည်းနဲ့ ဝိုင်းထားပါတယ်။ Line 9 "102,Math,120" ရောက်တဲ့အခါ InvalidScoreException တက်ပြီး control က loop အပြင်က catch ကို ခုန်သွားပါတယ်။ Error message တစ်ကြောင်း ထွက်ပေမယ့် line 10 ကနေ 13 အထိ ဘယ်တော့မှ မဖတ်တော့ပါဘူး။ Line 13 က Ko Ko ရဲ့ Math ကို 61 လို့ မှန်မှန်ကန်ကန် ပြင်ထားတဲ့ line ဖြစ်ပေမယ့် ပျောက်သွားပါတယ်။

Line 9 ကို ပြင်လိုက်ရင်တောင် line 11 "abc" က ပိုဆိုးပါတယ်။ Integer.parseInt() က NumberFormatException ပစ်ပြီး ဒီ catch က InvalidScoreException ကိုပဲ ဖမ်းလို့ program တစ်ခုလုံး stack trace နဲ့ ရပ်သွားနိုင်ပါတယ်။ addScoreSafe() call နှစ်ခုကို try တစ်ခုတည်းထဲ ထည့်ထားတဲ့အခါမှာလည်း ဒီပြဿနာက အသေးစားပုံစံနဲ့ ပေါ်ပါတယ်၊ ပထမ call မှားရင် ဒုတိယ call က မ run တော့ပါဘူး။

Draft.java
try {
    for (String line : lines) {
        String[] p = line.split(",");
        manager.recordScore(Integer.parseInt(p[0]), p[1], Integer.parseInt(p[2]));
    }
} catch (InvalidScoreException e) {           // first bad score ends the loop
    System.out.println("Error: " + e.getMessage());
}                                             // "abc" -> NumberFormatException escapes

ဘာကြောင့် ကျန်တဲ့ line တွေ ပျောက်တာလဲ

Exception တက်တဲ့အခါ Java က လက်ရှိ statement ကို ချက်ချင်း ရပ်ပြီး အနီးဆုံး ကိုက်ညီတဲ့ catch ကို ရှာပါတယ်။ Catch က loop အပြင်မှာ ရှိနေရင် loop ကိုပါ ထွက်သွားပြီး ပြန်မဝင်တော့ပါဘူး။ Try block ရဲ့ scope က "error တစ်ခု ဖြစ်ရင် ဘယ်လောက်အထိ လက်လျှော့မလဲ" ဆိုတာကို ဆုံးဖြတ်ပါတယ်။ Record တစ်ခုစီကို သီးခြား လက်လျှော့ချင်ရင် try ကို loop ထဲ ထည့်ရပါမယ်။

Core concept: exception က rule ချိုးဖောက်တာကို caller ဆီ ပို့တဲ့ နည်း

Part 2 ရဲ့ addScore() က ဘာ score မဆို လက်ခံပါတယ်။ Part 3 မှာ "score က 0 ကနေ 100 အထိပဲ" ဆိုတဲ့ rule ကို ထည့်ချင်ပါတယ်။ ဒါပေမယ့် Student class က console ကို print ထုတ်တာ၊ line နံပါတ် သိတာ မဖြစ်သင့်ပါဘူး။ Rule ကို စစ်တဲ့ နေရာနဲ့ error ကို user ဆီ ပြတဲ့ နေရာ ခွဲထားပြီး ကြားမှာ exception က သတင်းပို့ပေးပါတယ်။

၁။ Exception class ကိုယ်ပိုင် ရေးပါ

InvalidScoreException extends Exception က constructor ထဲမှာ super(message) ကို ခေါ်ရုံပါပဲ။ Class နာမည်ကိုယ်တိုင်က "ဘာမှားတာလဲ" ကို ပြောလို့ catch block တွေက error အမျိုးအစားအလိုက် ခွဲပြီး ကိုင်တွယ်နိုင်ပါတယ်။ StudentNotFoundException က id ကို ယူပြီး message ကို ကိုယ်တိုင် ဆောက်ပါတယ်။

၂။ Rule ကို data နားမှာ စစ်ပါ

Range check ကို Student.addScore() ထဲ ရွှေ့ထားလို့ score ထည့်တဲ့ လမ်းကြောင်း ဘယ်ကနေလာလာ ကျော်လို့ မရပါဘူး။ Part 2 မှာ getScores() ကို unmodifiable view ပဲ ပေးခဲ့တာ ဒီအတွက်ပါ။

၃။ throws က contract ပါ

Exception ကို extend လုပ်ထားတဲ့ checked exception ကို ပစ်တဲ့ method က signature မှာ throws ကို ရေးရပါတယ်။ Caller တိုင်းက catch လုပ်ရမလား၊ ကိုယ့် signature မှာ throws ဆက်ရေးရမလား ရွေးရပါတယ်။ addScore() ကို ပြောင်းလိုက်တာနဲ့ handle မလုပ်ထားတဲ့ caller တိုင်းကို compiler က error ပြပါတယ်။

၄။ Record တစ်ခုချင်းကို သီးခြား try လုပ်ပါ

Try ကို loop ထဲထည့်ထားလို့ line တစ်ကြောင်း မှားရင် အဲဒီ line ကိုပဲ reject လုပ်ပြီး နောက် line ကို ဆက်သွားပါတယ်။ Multi-catch (A | B) က handling တူတဲ့ exception နှစ်မျိုးကို တစ်ခါတည်း ဖမ်းပါတယ်။ NumberFormatException က unchecked ဖြစ်လို့ compiler က မတောင်းပေမယ့် user input ဆိုတာ မှားနိုင်လို့ ကိုယ်တိုင် ဖမ်းထားပါတယ်။

ExceptionChecked လားဒီ project မှာ
InvalidScoreExceptionChecked (extends Exception)0-100 ပြင်ပ score
StudentNotFoundExceptionChecked (extends Exception)မရှိတဲ့ id
NumberFormatExceptionUnchecked (RuntimeException)"abc" ကို parse လုပ်တာ
IllegalArgumentExceptionUnchecked (RuntimeException)Part 1 constructor validation
Mental model: line ဖတ်၊ စစ်၊ ဖယ် ဒါမှမဟုတ် သိမ်း
  1. Line ကို field သုံးခု ခွဲ
  2. Number တွေကို parse လုပ်
  3. recordScore() က rule ချိုးရင် throw
  4. Catch က line ကို reject လုပ်ပြီး ဆက်
  5. အကုန်ပြီးမှ copy ကို စီပြီး report

Try block ရဲ့ အရွယ်အစားက error တစ်ခုမှာ အလုပ် ဘယ်လောက် လက်လျှော့မလဲ ဆိုတာနဲ့ ညီရပါမယ်။

အခြေခံ ပုံစံ

java
class DomainException extends Exception {
    DomainException(String message) { super(message); }
}

void apply(Input in) throws DomainException {
    if (!valid(in)) throw new DomainException("why it failed: " + in);
}

for (Input in : batch) {
    try { apply(in); ok++; }
    catch (DomainException | NumberFormatException e) { report(in, e); }
}

Rule ချိုးတာကို method က throw လုပ်ပြီး throws နဲ့ ကြေညာပါ။ Batch ကို ဖတ်တဲ့ loop က item တစ်ခုချင်းကို try လုပ်ပြီး fail ဖြစ်တာကို report လုပ်ကာ ဆက်သွားပါတယ်။

Part 3 code: input ဖတ်ပြီး Final Report ထုတ်ခြင်း

ဒီ example က Part 1 နဲ့ Part 2 ရဲ့ class အားလုံးကို ဆက်ထားပြီး "NEW" နဲ့ "CHANGED" လို့ မှတ်ထားတဲ့ နေရာတွေကိုပဲ ပြင်ထားပါတယ်။ Student class ကိုလည်း file ထဲမှာ ဆက်ထည့်ထားရပါမယ်၊ မပါရင် compile မဖြစ်ပါဘူး။ printReport() က manager ရဲ့ list အစစ်ကို မထိဘဲ copy တစ်ခုကို sort လုပ်လို့ report ထုတ်ရုံနဲ့ တခြားနေရာက မြင်ရတဲ့ order မပြောင်းပါဘူး။ Keyboard input (Scanner) အစား lines array ကို သုံးထားလို့ run တိုင်း output တူပါတယ်။ Line 13 ရဲ့ correction က line 9-12 မှားနေတာတောင် ဝင်သွားတာကို ကြည့်ပါ။

StudentApp.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class StudentApp {
    public static void main(String[] args) {
        StudentManager manager = new StudentManager();
        manager.addStudent(new Student("Aung Aung", 101));
        manager.addStudent(new Student("Su Su", 102));
        manager.addStudent(new Student("Ko Ko", 103));
        manager.addStudent(new Student("Mya Mya", 104));

        // Scripted input: one "id,subject,score" record per line.
        String[] lines = {
            "101,Math,95", "101,English,82", "101,Science,88",
            "102,Math,72", "102,English,91", "102,Science,67",
            "103,Math,45", "103,English,58",
            "102,Math,120",      // score out of range
            "105,Math,80",       // no such student
            "103,Science,abc",   // not a number
            "103,Math",          // missing field
            "103,Math,61",       // a valid correction
        };

        int accepted = 0;
        for (int i = 0; i < lines.length; i++) {
            String where = "Line " + (i + 1);
            String[] parts = lines[i].split(",");
            if (parts.length != 3) {
                System.out.println(where + " skipped: expected id,subject,score");
                continue;
            }
            try {
                int id = Integer.parseInt(parts[0].strip());
                int score = Integer.parseInt(parts[2].strip());
                manager.recordScore(id, parts[1].strip(), score);
                accepted++;
            } catch (InvalidScoreException | StudentNotFoundException e) {
                System.out.println(where + " rejected: " + e.getMessage());
            } catch (NumberFormatException e) {
                System.out.println(where + " rejected: not a number");
            }
        }
        System.out.println("Accepted " + accepted + " of " + lines.length + " lines");
        System.out.println();
        manager.printReport();
    }
}

// NEW in Part 3: two checked exceptions for bad input ------------
class InvalidScoreException extends Exception {
    public InvalidScoreException(String message) {
        super(message);
    }
}

class StudentNotFoundException extends Exception {
    public StudentNotFoundException(int id) {
        super("no student with id " + id);
    }
}

class Student {
    private final String name;
    private final int id;
    private final Map<String, Integer> subjectScores;

    public Student(String name, int id) {
        if (name == null || name.isBlank()) {
            throw new IllegalArgumentException("name must not be blank");
        }
        if (id <= 0) {
            throw new IllegalArgumentException("id must be positive, got " + id);
        }
        this.name = name.strip();
        this.id = id;
        this.subjectScores = new LinkedHashMap<>();
    }

    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }

    // CHANGED in Part 3: the range rule now lives here, so no caller can skip it
    public void addScore(String subject, int score) throws InvalidScoreException {
        if (score < 0 || score > 100) {
            throw new InvalidScoreException(
                    subject + " score must be 0-100, got: " + score);
        }
        subjectScores.put(subject, score);
    }

    public Map<String, Integer> getScores() {
        return Collections.unmodifiableMap(subjectScores);
    }

    public double calculateAverage() {
        if (subjectScores.isEmpty()) {
            return 0.0;
        }
        int total = 0;
        for (int score : subjectScores.values()) {
            total += score;
        }
        return (double) total / subjectScores.size();
    }

    public String getGrade() {
        if (subjectScores.isEmpty()) {
            return "-";
        }
        double avg = calculateAverage();
        if (avg >= 90) {
            return "A";
        } else if (avg >= 75) {
            return "B";
        } else if (avg >= 50) {
            return "C";
        } else {
            return "F";
        }
    }
}

class StudentManager {
    private final List<Student> students = new ArrayList<>();

    public boolean addStudent(Student student) {
        if (findById(student.getId()) != null) {
            return false;
        }
        students.add(student);
        return true;
    }

    public Student findById(int id) {
        for (Student s : students) {
            if (s.getId() == id) {
                return s;
            }
        }
        return null;
    }

    // NEW in Part 3 ------------------------------------------------
    public void recordScore(int id, String subject, int score)
            throws InvalidScoreException, StudentNotFoundException {
        Student student = findById(id);
        if (student == null) {
            throw new StudentNotFoundException(id);
        }
        student.addScore(subject, score);
    }

    public void printReport() {
        List<Student> ranked = new ArrayList<>(students); // sort a copy
        ranked.sort(Comparator.comparingDouble(Student::calculateAverage).reversed()
                .thenComparing(Student::getName));

        System.out.println("---- Final Report ----");
        System.out.printf("%-10s %6s  %s%n", "Name", "Avg", "Grade");
        for (Student s : ranked) {
            if (s.getScores().isEmpty()) {
                System.out.printf("%-10s %6s  %s%n", s.getName(), "n/a", s.getGrade());
            } else {
                System.out.printf("%-10s %6.1f  %s%n",
                        s.getName(), s.calculateAverage(), s.getGrade());
            }
        }
    }
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. A checked exception of our ownclass InvalidScoreException extends Exception {

    Exception ကို extend လုပ်လို့ checked exception ဖြစ်ပါတယ်။ RuntimeException ကို extend လုပ်ခဲ့ရင် unchecked ဖြစ်ပြီး compiler က caller ကို handle လုပ်ခိုင်းမှာ မဟုတ်ပါဘူး။

  2. The rule moves into Studentpublic void addScore(String subject, int score) throws InvalidScoreException {

    Range check ကို ဒီမှာ ထားလို့ 120 က map ထဲ ဘယ်တော့မှ မရောက်ပါဘူး။ throws ကြောင့် recordScore() ကလည်း သူ့ signature မှာ throws ဆက်ကြေညာရပါတယ်။

  3. A try per linemanager.recordScore(id, parts[1].strip(), score);

    ဒီ call က loop ထဲက try block ထဲမှာ ရှိလို့ exception တက်ရင် accepted++ ကို ကျော်ပြီး catch ကို ရောက်၊ ပြီးရင် နောက် line ကို ဆက်သွားပါတယ်။

  4. Multi-catch} catch (InvalidScoreException | StudentNotFoundException e) {

    Handling တူတဲ့ exception နှစ်မျိုးကို catch တစ်ခုတည်းနဲ့ ဖမ်းပါတယ်။ getMessage() က exception ဆောက်တုန်းက ပေးခဲ့တဲ့ message ကို ပြန်ပေးပါတယ်။

  5. Sort a copy, highest firstranked.sort(Comparator.comparingDouble(Student::calculateAverage).reversed()

    comparingDouble က average အငယ်ကနေ စီပြီး reversed() က အကြီးကနေ ဖြစ်အောင် လှန်ပါတယ်။ ranked က copy ဖြစ်လို့ manager ရဲ့ list order မပြောင်းပါဘူး။ thenComparing(Student::getName) က average တူရင် နာမည်နဲ့ စီပါတယ်။

You should see
Line 9 rejected: Math score must be 0-100, got: 120
Line 10 rejected: no student with id 105
Line 11 rejected: not a number
Line 12 skipped: expected id,subject,score
Accepted 9 of 13 lines

---- Final Report ----
Name          Avg  Grade
Aung Aung    88.3  B
Su Su        76.7  B
Ko Ko        59.5  C
Mya Mya       n/a  -
Input line တစ်ကြောင်းရဲ့ လမ်းကြောင်း
  1. split(",") နဲ့ field ခွဲ
  2. Field ၃ ခု မဟုတ်ရင် skip
  3. parseInt() နဲ့ id၊ score ယူ
  4. recordScore() → findById() → addScore()

Rule အားလုံး ကိုက်

score stored, accepted++

Exception တက်

Line N rejected: <message>

printf နဲ့ locale

%-10s က နာမည်ကို စာလုံး ၁၀ လုံးစာ နေရာမှာ ဘယ်ဘက်ကပ်ပြီး %6.1f က number ကို ဒဿမ တစ်နေရာနဲ့ စာလုံး ၆ လုံးစာ နေရာမှာ ညာဘက်ကပ်ပါတယ်။ ဒါကြောင့် column တွေ တန်းညီပါတယ်။

သတိထားရမှာက printf နဲ့ String.format က computer ရဲ့ default locale ကို သုံးတာပါ။ German locale ရှိတဲ့ စက်မှာ 88.3 က 88,3 ဖြစ်သွားပါတယ်။ လူဖတ်ဖို့ report အတွက် ဒါက ကောင်းပေမယ့် CSV လို စက်ကဖတ်မယ့် file အတွက်ဆိုရင် String.format(Locale.ROOT, ...) နဲ့ locale ကို ပုံသေ သတ်မှတ်ပါ။

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ

CSV import၊ bank statement upload၊ အမှတ်စာရင်း bulk upload စတဲ့ feature တွေ အားလုံးက ဒီ pattern အတိုင်းပါ။ Row တစ်ခုချင်းကို validate လုပ်၊ မှန်တာကို သိမ်း၊ မှားတာကို row နံပါတ်နဲ့ အကြောင်းရင်းပါတဲ့ error list ထဲ ထည့်ပြီး နောက်ဆုံးမှာ "9 of 13 accepted" လို summary ပြပါတယ်။ User က မှားတဲ့ row လေးကြောင်းကိုပဲ ပြင်ပြီး ပြန်တင်ရုံပါ။

တချို့ system တွေကတော့ "all or nothing" ကို လိုချင်ပါတယ်။ ဥပမာ ငွေလွှဲ batch မှာ တစ်ကြောင်း မှားရင် ဘာမှ မသိမ်းဘဲ အကုန် rollback လုပ်ရပါတယ်။ အဲဒီလိုဆိုရင် အရင်ဆုံး row အားလုံးကို validate လုပ်ပြီး error မရှိမှ သိမ်းပါတယ်။ ဘယ် policy ကို သုံးမလဲဆိုတာ business က ဆုံးဖြတ်ရမှာဖြစ်ပြီး code မှာ ထင်ထင်ရှားရှား ရေးထားရပါမယ်။ Report ကို file ထဲ သိမ်းမယ်ဆိုရင်လည်း temporary file ထဲ အရင်ရေးပြီး Files.move() နဲ့ အစားထိုးတာက ရေးနေတုန်း crash ဖြစ်ရင် file အဟောင်း မပျက်အောင် ကာကွယ်ပေးပါတယ်။

အမှားများ

ဖြစ်လေ့ရှိတဲ့ အမှားများ

throws ကို signature မှာ မေ့တာ

addScore() ထဲမှာ throw new InvalidScoreException(...) ရေးပြီး throws မကြေညာရင် "unreported exception InvalidScoreException; must be caught or declared to be thrown" ဆိုတဲ့ compile error ရပါတယ်။ ဒါက bug မဟုတ်ပါဘူး၊ checked exception ရဲ့ ရည်ရွယ်ချက်ပါ။

Try ကို loop အပြင်မှာ ထားတာ

Problem section မှာ မြင်ခဲ့သလို ပထမ error မှာ loop ကနေ ထွက်သွားပြီး နောက်က မှန်တဲ့ line တွေ ပျောက်ပါတယ်။ Item တစ်ခုချင်း ဆက်လုပ်ချင်ရင် try ကို loop body ထဲ ထည့်ပါ။

catch (Exception e) နဲ့ အကုန်ဖမ်းတာ

catch (Exception e) က code ထဲက တကယ့် bug (ဥပမာ NullPointerException) ကိုပါ "input မှားတယ်" လို့ ဖုံးပစ်ပါတယ်။ ကြိုတင်မြင်ထားတဲ့ exception အမျိုးအစားတွေကိုပဲ နာမည်နဲ့ ဖမ်းပါ။

Manager ရဲ့ list အစစ်ကို sort လုပ်တာ

printReport() ထဲမှာ students.sort(...) ကို တိုက်ရိုက် ခေါ်ရင် report ထုတ်ရုံနဲ့ roster ရဲ့ order ပြောင်းသွားပြီး "print" method က side effect ဖြစ်စေပါတယ်။ new ArrayList<>(students) နဲ့ copy လုပ်ပြီးမှ sort ပါ။

Mini challenge

Report ကို CSV file အဖြစ် export လုပ်ပါ

exportCsv(List<ReportRow> rows, Path file) ကို ရေးပါ။ Header line နဲ့ row တစ်ခုစီကို UTF-8 နဲ့ file ထဲ ရေးပြီး try-with-resources နဲ့ writer ကို အမြဲ ပိတ်ပါ။ main က temporary file တစ်ခု ဆောက်၊ export လုပ်၊ ပြန်ဖတ်ပြီး print ထုတ်၊ နောက်ဆုံးမှာ file ကို ဖျက်ပါ။

  • exportCsv() က IOException ကို throws နဲ့ ကြေညာပြီး ကိုယ်တိုင် မဖမ်းရပါ
  • Average ကို Locale.ROOT နဲ့ ဒဿမ တစ်နေရာ format လုပ်ပါ (88.3၊ 88,3 မဟုတ်)
  • main က IOException ကို catch လုပ်ပြီး temp file ကို finally ထဲမှာ ဖျက်ပါ
  • Temp file ရဲ့ path ကို print မထုတ်ပါနဲ့ (run တိုင်း ပြောင်းလို့)
ExportChallenge.java
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;

public class ExportChallenge {
    static void exportCsv(List<ReportRow> rows, Path file) throws IOException {
        // TODO: try (BufferedWriter out = Files.newBufferedWriter(file, UTF_8)) {
        //   header "id,name,average,grade", then one line per row
        // }
    }

    public static void main(String[] args) {
        // TODO: build three rows, create a temp file, export, read back, print,
        // and delete the file in finally
    }
}

record ReportRow(int id, String name, double average) {
    String grade() { /* TODO: same thresholds as Part 2 */ return "?"; }
}

ရလဒ်: "Wrote 4 lines:" ပြီးနောက် header တစ်ကြောင်းနဲ့ 101,Aung Aung,88.3,B / 102,Su Su,76.7,B / 103,Ko Ko,59.5,C ဆိုတဲ့ row သုံးကြောင်း ထွက်ပါမယ်။

အရိပ်အမြွက် ကြည့်ရန်

Files.createTempFile("report", ".csv") က file အလွတ်တစ်ခု ဆောက်ပေးပါတယ်။ Files.readAllLines(file, StandardCharsets.UTF_8) နဲ့ ပြန်ဖတ်ပါ။ Record ရဲ့ field တွေကို id()၊ name()၊ average() method တွေနဲ့ ဖတ်ရပါတယ်။

အဖြေ ကြည့်ရန်
ExportChallenge.java
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;

public class ExportChallenge {
    static void exportCsv(List<ReportRow> students, Path file) throws IOException {
        try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
            out.write("id,name,average,grade");
            out.newLine();
            for (ReportRow s : students) {
                out.write(String.format(Locale.ROOT, "%d,%s,%.1f,%s",
                        s.id(), s.name(), s.average(), s.grade()));
                out.newLine();
            }
        } // the writer is flushed and closed here, even if write() throws
    }

    public static void main(String[] args) {
        List<ReportRow> students = List.of(
                new ReportRow(101, "Aung Aung", 88.33),
                new ReportRow(102, "Su Su", 76.67),
                new ReportRow(103, "Ko Ko", 59.5));
        Path file = null;
        try {
            file = Files.createTempFile("report", ".csv");
            exportCsv(students, file);
            List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
            System.out.println("Wrote " + lines.size() + " lines:");
            lines.forEach(System.out::println);
        } catch (IOException e) {
            System.out.println("Export failed: " + e.getMessage());
        } finally {
            if (file != null) {
                try {
                    Files.deleteIfExists(file);
                } catch (IOException ignored) {
                    // nothing useful to do if cleanup fails
                }
            }
        }
    }
}

record ReportRow(int id, String name, double average) {
    String grade() {
        if (average >= 90) return "A";
        if (average >= 75) return "B";
        if (average >= 50) return "C";
        return "F";
    }
}

Quick Quiz 1 / 3

class InvalidScoreException extends RuntimeException လို့ ပြောင်းလိုက်ရင် ဘာဖြစ်မလဲ။

Quick Quiz 2 / 3

Try block ကို for loop တစ်ခုလုံးရဲ့ အပြင်မှာ ထားပြီး line 9 မှာ InvalidScoreException တက်ရင် line 13 ရဲ့ correction က ဘာဖြစ်မလဲ။

Quick Quiz 3 / 3

Average တွေ 88.3၊ 76.7၊ 59.5 ရှိပြီး Comparator.comparingDouble(Student::calculateAverage) နဲ့ပဲ (reversed() မပါဘဲ) စီရင် ပထမဆုံး ဘယ်သူ ပေါ်မလဲ။

မှတ်ထားရမယ့် အချက်များ

  • Custom checked exception က Exception ကို extend လုပ်ပြီး super(message) ကို ခေါ်ရုံပါ
  • Rule ကို data နားမှာ (Student.addScore()) စစ်ပြီး throws နဲ့ caller တွေကို အသိပေးပါ
  • Try ကို item တစ်ခုချင်းစီ ဝိုင်းထားရင် မှားတဲ့ line တစ်ကြောင်းက batch ကို မရပ်စေတော့ပါ
  • Report အတွက် copy ကို reversed() နဲ့ thenComparing() သုံးပြီး စီပါ

Java Language Specification, Java SE 25 — Oracle

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Student Manager Project - Part 3: Exceptions & Final Report | Thuta Learning