Membuat Fungsi Clear Screen di Java
66 / 100

Create a TodoList Application (CRUD) with Java and Files

Creating a New Class

Create a TodoList Application (CRUD) with Java and Files, Create a new class in the project AplikasiFile by the name TodoListApp.

Membuat Class TodoListApp

Then fill it with the following code:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class TodoListApp {

    // deklarasi variabel global
    static String fileName;
    static ArrayList<String> todoLists;
    static boolean isEditing = false;
    static Scanner input;

    public static void main(String[] args) {
        
    }
    
    static void clearScreen(){
    }

    static void showMenu() {
    }

    static void backToMenu() {
    }

    static void readTodoList() {
    }

    static void showTodoList() {
    }

    static void addTodoList() {
    }

    static void editTodoList() {
    }

    static void deleteTodoList() {
    }

}

Create a Clear Screen Function in Java

This function we need to clean the screen. Please fill in the code for the function clearScreen() such as the following:

static void clearScreen() {
    try {
        final String os = System.getProperty("os.name");
        if (os.contains("Windows")) {
            // clear screen untuk windows
            new ProcessBuilder("cmd", "/c", "cls")
                    .inheritIO()
                    .start()
                    .waitFor();
        } else {
            // clear screen untuk Linux, Unix, Mac
            Runtime.getRuntime().exec("clear");
            System.out.print("3[H3[2J");
            System.out.flush();
        }
    } catch (final Exception e) {
        System.out.println("Error karena: " + e.getMessage());
    }
}

If we pay attention, this function will execute the command cls and celar.

If you open this program from Windows, then the order cls which will be used. And clear for Linux, Unix, and Mac.

But this function can't work on output window in Netbeans.

Creating a Function showMenu()

Next we need a function showMenu() to display any menu in the application.

Please fill in the code for the function showMenu() such as the following:

static void showMenu() {
    System.out.println("=== TODO LIST APP ===");
    System.out.println("[1] Lihat Todo List");
    System.out.println("[2] Tambah Todo List");
    System.out.println("[3] Edit Todo List");
    System.out.println("[4] Hapus Todo List");
    System.out.println("[0] Keluar");
    System.out.println("---------------------");
    System.out.print("Pilih menu> ");

    String selectedMenu = input.nextLine();

    if (selectedMenu.equals("1")) {
        showTodoList();
    } else if (selectedMenu.equals("2")) {
        addTodoList();
    } else if (selectedMenu.equals("3")) {
        editTodoList();
    } else if (selectedMenu.equals("4")) {
        deleteTodoList();
    } else if (selectedMenu.equals("0")) {
        System.exit(0);
    } else {
        System.out.println("Kamu salah pilih menu!");
        backToMenu();
    }
}

In addition to displaying the menu, this function will also determine which function will be executed when the menu is selected.

Example, the user selects the menu 1, then the function showTodoList() to be executed.

Creating a Function backToMenu()

We need this function to return to the Main Menu. Please fill in the code inside the function backToMenu() like this:

static void backToMenu() {
    System.out.println("");
    System.out.print("Tekan [Enter] untuk kembali..");
    input.nextLine();
    clearScreen();
}

This function will ask the user to press Enter. After that it will clear the screen and open the Main menu.

Although we do not call the function showMenu() over there, but still going back to the menu.

This is because we will return to main loop.

What's that main loop?

Later we will create and discuss..

Creating a Function readTodoList()

We need this function to read the contents of the File. Please fill in the code for the function readTodoList() such as the following:

static void readTodoList() {
    try {
        File file = new File(fileName);
        Scanner fileReader = new Scanner(file);

        // load isi file ke dalam array todoLists
        todoLists.clear();
        while (fileReader.hasNextLine()) {
            String data = fileReader.nextLine();
            todoLists.add(data);
        }

    } catch (FileNotFoundException e) {
        System.out.println("Error karena: " + e.getMessage());
    }
}

This function will read the file, then the contents will be stored in an array variable todoLists.

We will call this function when we want to reread the contents of the file.

Creating a Function showTodoList()

This function we need to display the contents of the file todolist.txt.

Please fill in the function code showTodoList() such as the following:

static void showTodoList() {
    clearScreen();
    readTodoList();
    if (todoLists.size() > 0) {
        System.out.println("TODO LIST:");
        int index = 0;
        for (String data : todoLists) {
            System.out.println(String.format("[%d] %s", index, data));
            index++;
        }
    } else {
        System.out.println("Tidak ada data!");
    }

    if (!isEditing) {
        backToMenu();
    }
}

This function only prints or prints the contents of the file. We call a function readTodoList() here, to read the contents of the file.

Creating a Function addTodoList()

Next, please fill in the code for the function addTodoList() like this:

static void addTodoList() {
    clearScreen();

    System.out.println("Apa yang ingin kamu kerjakan?");
    System.out.print("Jawab: ");
    String newTodoList = input.nextLine();

    try {
        // tulis file
        FileWriter fileWriter = new FileWriter(fileName, true);
        fileWriter.append(String.format("%s%n", newTodoList));
        fileWriter.close();
        System.out.println("Berhasil ditambahkan!");
    } catch (IOException e) {
        System.out.println("Terjadi kesalahan karena: " + e.getMessage());
    }

    backToMenu();
}

This function will ask the user to input the todo list data, then write it into a file.

Creating a Function editTodoList()

We need this function to change the contents of the data. Please fill in the code for the function editTodoList() such as the following:

static void editTodoList() {
    isEditing = true;
    showTodoList();

    try {
        System.out.println("-----------------");
        System.out.print("Pilih Indeks> ");
        int index = Integer.parseInt(input.nextLine());

        if (index > todoLists.size()) {
            throw new IndexOutOfBoundsException("Kamu memasukan data yang salah!");
        } else {

            System.out.print("Data baru: ");
            String newData = input.nextLine();

            // update data
            todoLists.set(index, newData);

            System.out.println(todoLists.toString());

            try {
                FileWriter fileWriter = new FileWriter(fileName, false);

                // write new data
                for (String data : todoLists) {
                    fileWriter.append(String.format("%s%n", data));
                }
                fileWriter.close();

                System.out.println("Berhasil diubah!");
            } catch (IOException e) {
                System.out.println("Terjadi kesalahan karena: " + e.getMessage());
            }
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    isEditing = false;
    backToMenu();
}

How this function works there are several steps:

  1. Asks the user to select an index number from the data (index in array todolist)
  2. Check the index
  3. Asking the user to enter new data
  4. Storing new data into an array todolist
  5. Rewrite all array contents todolist into file

Creating a Function deleteTodoList()

We need this function to delete todolist data. Please write the code for the function deleteTodoList() such as the following.

static void deleteTodoList() {
    isEditing = true;
    showTodoList();

    System.out.println("-----------------");
    System.out.print("Pilih Indeks> ");
    int index = Integer.parseInt(input.nextLine());

    try {
        if (index > todoLists.size()) {
            throw new IndexOutOfBoundsException("Kamu memasukan data yang salah!");
        } else {

            System.out.println("Kamu akan menghapus:");
            System.out.println(String.format("[%d] %s", index, todoLists.get(index)));
            System.out.println("Apa kamu yakin?");
            System.out.print("Jawab (y/t): ");
            String jawab = input.nextLine();

            if (jawab.equalsIgnoreCase("y")) {
                // hapus data
                todoLists.remove(index);

                // tulis ulang file
                try {
                    FileWriter fileWriter = new FileWriter(fileName, false);

                    // write new data
                    for (String data : todoLists) {
                        fileWriter.append(String.format("%s%n", data));
                    }
                    fileWriter.close();

                    System.out.println("Berhasil dihapus!");
                } catch (IOException e) {
                    System.out.println("Terjadi kesalahan karena: " + e.getMessage());
                }
            }
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    isEditing = false;
    backToMenu();
}

How the function works deleteTodoList() also almost the same as editTodoList().

Initializing and Main Loop

Final, we have to make initialization and main loop on the function main().

Please write the code for the function main() such as the following.

public static void main(String[] args) {
    // initialize
    todoLists = new ArrayList<>();
    input = new Scanner(System.in);

    String filePath = System.console() == null ? "/src/todolist.txt" : "/todolist.txt";
    fileName = System.getProperty("user.dir") + filePath;

    System.out.println("FILE: " + fileName);

    // run the program (main loop)
    while (true) {
        showMenu();
    }
}

First we have to initialize or fill in the first value for each global variable that doesn't have content so that it doesn't happen NullPointerException.

To determine the location of the file to be read, we write it like this:

String filePath = System.console() == null ? "/src/todolist.txt" : "/todolist.txt";
fileName = System.getProperty("user.dir") + filePath;

Because later we will try to open the application from outside and inside Netbeans.

because, file address (path) what you read on Netbeans is different from what you read on the outside.

Final, we make main loop keep the program from stopping as long as we don't close it.

source : https://www.petanikode.com/java-file-crud/

 1,378 total views,  6 views today

By admin

Writer

Leave a Reply

Your email address will not be published.

Web Hosting Murah Yang Terbaik Di Indonesia