---
# System prepended metadata

title: 簡單互動式管理系統 - ArrayList增刪改查的應用
tags: [Java, Basic Java]

---

# 簡單互動式管理系統 - ArrayList增刪改查的應用
###### tags: `Java` `Basic Java`

## 首先建立一個domain的資料夾，裡面放入Java Bean
通常Java Bean都放在domain裡統一管理
將屬性參數都設定private後，直接用IDE自動生成getter & setter

```
package domain;

public class Student {
    private String id;
    private String name;
    private int age;
    private String birthday;


    public Student() {
    }

    public Student(String id, String name, int age, String birthday) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String toString() {
        return "Student{id = " + id + ", name = " + name + ", age = " + age + ", birthday = " + birthday + "}";
    }
}

```
## 主程式部分
幾個重點：
1. 選項有限，故使用switch case進行選單操作
2. 因為要重複跟user提取其輸入的數字，故需要用while來實現

```
    public static void main(String[] args) {
    
        // 建立一個arraylist以存放data 資料成員是學生類別
        ArrayList<Student> studentList = new ArrayList<>();

        Scanner sc = new Scanner(System.in);
        
        // 使用while(true)迴圈讓scanner能夠重複執行
        while (true) {
            System.out.println("*** Welcome To The System ***");
            System.out.println("Please Enter a Number: ");
            System.out.println("1. Add a Entry");
            System.out.println("2. Delete a Entry");
            System.out.println("3. Edit a Entry");
            System.out.println("4. Show All Entries");
            System.out.println("5. Leave System");

            int choice = sc.nextInt();

            switch (choice) {
                case 1:
                    addEntries(studentList);
                    break;

                case 2:
                    deleteEntries(studentList);
                    break;

                case 3:
                    editEntries(studentList);

                    break;

                case 4:
                    queryEntries(studentList);
                    break;

                case 5:
                    System.out.println("Thank you and Goodbye!");
                    System.exit(0);
                    break;

                default:
                    System.out.println("Invalid Input. Please Try Again!");
                    break;
            }
        }

    }

```

## 增刪改查：各自寫成方法方便維護與管理

為防止任意使用，故將成員方法都用private修飾

### 新增：
```
    private static void addEntries(ArrayList<Student> studentList) {
        // 參數宣告初始化
        String inputID = "";
        Scanner sc = null;
        
        // 判斷重複資料
        // 跟user要求資料，若查詢到重覆值則繼續要求輸入，故使用while(true)迴圈，脫離迴圈的方式是查不到存放資料的arraylist中的數據(也就是回傳index為-1)
        while (true) {
            sc = new Scanner(System.in);
            System.out.println("Please Enter Student ID: ");
            inputID = sc.next();
            
            // 調用getIndex的方法
            int index = getIndex(inputID, studentList);
            if (index == -1) {
                break;
            }
            System.out.println("ID was occupied. Please Re-enter A New ID.\n");
        }
        
        // 登錄資料
        System.out.println("Please Enter Student Name: ");
        String inputName = sc.next();
        System.out.println("Please Enter Student Age: ");
        int inputAge = sc.nextInt();
        System.out.println("Please Enter Student Birthday: ");
        String inputBirthday = sc.next();
        
        // 登錄資料存進參數，然後用學生類的constructor生成學生物件
        // 再放入arraylist當中
        Student stu = new Student(inputID, inputName, inputAge, inputBirthday);

        studentList.add(stu);
        System.out.println("Added Successfully.");

    }
```

### 修改：
```
    private static void editEntries(ArrayList<Student> studentList) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please Enter an ID to be Edited: ");     
        // 使用index查找資料，若返回-1則代表沒找到
        String input = sc.next();
        
        // 調用getIndex的方法
        int index = getIndex(input, studentList);
        if (index == -1) {
            System.out.println("Entry not Found. Please Re-enter.\n");
        } else {
            // take user input
            System.out.println("Please Enter A New ID: ");
            String newID = sc.next();
            System.out.println("Please Enter A New Name: ");
            String newName = sc.next();
            System.out.println("Please Enter A New Age: ");
            int newAge = sc.nextInt();
            System.out.println("Please Enter A New Birthday");
            String newBirthday = sc.next();

            // Edit new info with user input
            /* method 1
            studentList.get(index).setId(newID);
            studentList.get(index).setName(newName);
            studentList.get(index).setAge(newAge);
            studentList.get(index).setBirthday(newBirthday);
             */
             
            // method 2
            Student stu = new Student(newID, newName, newAge, newBirthday);
            studentList.set(index, stu);

            System.out.println("Edited Successfully.\n");
        }

    }
```

### 查詢：
```
    public static void queryEntries(ArrayList<Student> studentList) {
    
        // 一開始都沒有建立資料的時候查找會是0
        if (studentList.size() == 0) {
            System.out.println("No Entries Found. Please Enter Information.\n");
        } else {
        
        // 有資料後，就把所有資料都印出來
            System.out.println("ID\tName\tAge\tBirthday");
            for (int i = 0; i < studentList.size(); i++) {
                Student stu = studentList.get(i);
                System.out.print(stu.getId() + "\t");
                System.out.print(stu.getName() + "\t");
                System.out.print(stu.getAge() + "\t");
                System.out.print(stu.getBirthday() + "\t");
                System.out.println();
            }
            System.out.println("\n");

        }
    }
```

### 刪除：
```
    public static void deleteEntries(ArrayList<Student> studentList) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please Enter an ID to be Deleted: ");
        String input = sc.next();
        
        // 調用getIndex方法尋找資料
        int index = getIndex(input, studentList);
        if (index == -1) {
            System.out.println("Entry not Found. Please Re-enter.\n");
        } else {
        
        // 找到就進行remove
            studentList.remove(index);
            System.out.println("Removed Successfully.\n");
        }
    }
```

### 取得index的方法
由於新增、修改與刪除都需要取得學生資料在陣列中的位置，故需要另外做一個getIndex的方法，傳入學生ID與學生list，返回index，沒找到就返回-1
```
    public static int getIndex(String id, ArrayList<Student> studentList) {
        for (int i = 0; i < studentList.size(); i++) {
            Student stu = studentList.get(i);
            if (stu.getId().equals(id)) {
                return i;
            }

        }
        return -1;
    }
```

### Source Code
```
package org.example;

import domain.Student;

import java.util.ArrayList;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) {

        ArrayList<Student> studentList = new ArrayList<>();

        // testing data
        /*
        Student stu1 = new Student("001", "John", 25, "1999-01-01");
        Student stu2 = new Student("002", "Wick", 30, "1988-12-12");

        studentList.add(stu1);
        studentList.add(stu2);

         */


        Scanner sc = new Scanner(System.in);

        while (true) {
            System.out.println("*** Welcome To The System ***");
            System.out.println("Please Enter a Number: ");
            System.out.println("1. Add a Entry");
            System.out.println("2. Delete a Entry");
            System.out.println("3. Edit a Entry");
            System.out.println("4. Show All Entries");
            System.out.println("5. Leave System");

            int choice = sc.nextInt();

            switch (choice) {
                case 1:
                    addEntries(studentList);
                    break;

                case 2:
                    deleteEntries(studentList);
                    break;

                case 3:
                    editEntries(studentList);

                    break;

                case 4:
                    queryEntries(studentList);
                    break;

                case 5:
                    System.out.println("Thank you and Goodbye!");
                    System.exit(0);
                    break;

                default:
                    System.out.println("Invalid Input. Please Try Again!");
                    break;
            }
        }

    }

    private static void addEntries(ArrayList<Student> studentList) {

        String inputID = "";
        Scanner sc = null;

        while (true) {
            sc = new Scanner(System.in);
            System.out.println("Please Enter Student ID: ");
            inputID = sc.next();
            int index = getIndex(inputID, studentList);
            if (index == -1) {
                break;
            }
            System.out.println("ID was occupied. Please Re-enter A New ID.\n");
        }

        System.out.println("Please Enter Student Name: ");
        String inputName = sc.next();
        System.out.println("Please Enter Student Age: ");
        int inputAge = sc.nextInt();
        System.out.println("Please Enter Student Birthday: ");
        String inputBirthday = sc.next();

        Student stu = new Student(inputID, inputName, inputAge, inputBirthday);

        studentList.add(stu);
        System.out.println("Added Successfully.");

    }


    private static void editEntries(ArrayList<Student> studentList) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please Enter an ID to be Edited: ");
        String input = sc.next();
        int index = getIndex(input, studentList);
        if (index == -1) {
            System.out.println("Entry not Found. Please Re-enter.\n");
        } else {
            // take user input
            System.out.println("Please Enter A New ID: ");
            String newID = sc.next();
            System.out.println("Please Enter A New Name: ");
            String newName = sc.next();
            System.out.println("Please Enter A New Age: ");
            int newAge = sc.nextInt();
            System.out.println("Please Enter A New Birthday");
            String newBirthday = sc.next();

            // Edit new info with user input
            /* method 1
            studentList.get(index).setId(newID);
            studentList.get(index).setName(newName);
            studentList.get(index).setAge(newAge);
            studentList.get(index).setBirthday(newBirthday);

             */
            /* method 2
             */
            Student stu = new Student(newID, newName, newAge, newBirthday);
            studentList.set(index, stu);

            System.out.println("Edited Successfully.\n");
        }

    }


    public static void deleteEntries(ArrayList<Student> studentList) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please Enter an ID to be Deleted: ");
        String input = sc.next();
        int index = getIndex(input, studentList);
        if (index == -1) {
            System.out.println("Entry not Found. Please Re-enter.\n");
        } else {
            studentList.remove(index);
            System.out.println("Removed Successfully.\n");
        }
    }

    public static int getIndex(String id, ArrayList<Student> studentList) {
        for (int i = 0; i < studentList.size(); i++) {
            Student stu = studentList.get(i);
            if (stu.getId().equals(id)) {
                return i;
            }

        }
        return -1;
    }

    public static void queryEntries(ArrayList<Student> studentList) {

        if (studentList.size() == 0) {
            System.out.println("No Entries Found. Please Enter Information.\n");
        } else {
            System.out.println("ID\tName\tAge\tBirthday");
            for (int i = 0; i < studentList.size(); i++) {
                Student stu = studentList.get(i);
                System.out.print(stu.getId() + "\t");
                System.out.print(stu.getName() + "\t");
                System.out.print(stu.getAge() + "\t");
                System.out.print(stu.getBirthday() + "\t");
                System.out.println();
            }
            System.out.println("\n");

        }
    }
}

```