Monday, November 3, 2025

Pertemuan 11 | Unit Testing

 Naufal Daffa Alfa Zain                                                                                                           5025241066                                                                                                                                 Pemrograman Berorientasi Objek – A

Pada pertemuan kesebelas mata kuliah Pemrograman Berorientasi Objek (PBO A), kami melanjutkan latihan pemahaman konsep OOP dengan membuat program bernama SalesItem menggunakan bahasa Java di platform BlueJ. Program ini bertujuan untuk mensimulasikan sistem ulasan (review system) pada suatu produk, di mana pengguna dapat memberikan komentar, rating, serta melakukan upvote dan downvote terhadap komentar yang ada.

Program terdiri dari tiga kelas utama yaitu SalesItem, Comment, dan SalesItemTest. Kelas SalesItem berfungsi sebagai representasi suatu produk yang dijual, menyimpan nama barang, harga, serta daftar komentar yang diberikan pengguna. Kelas Comment merepresentasikan satu ulasan dari pengguna yang terdiri dari nama penulis, isi komentar, rating, dan jumlah suara. Sementara kelas SalesItemTest berperan sebagai kelas penguji yang menjalankan berbagai skenario untuk memastikan fungsi-fungsi dalam program berjalan sebagaimana mestinya.

Melalui program ini, pengguna dapat menambahkan komentar dengan validasi tertentu — seperti rating yang harus berada dalam rentang 1 hingga 5 dan tidak boleh ada dua komentar dari penulis yang sama. Selain itu, setiap komentar dapat diberi upvote atau downvote yang memengaruhi keseimbangan suara (vote balance). Program juga mampu menampilkan komentar yang dianggap paling membantu, yaitu komentar dengan nilai vote balance tertinggi.



Source Code Lengkap

SalesItem

import java.util.ArrayList;

public class SalesItem {
    private String name;
    private int price;
    private ArrayList<Comment> comments;

    public SalesItem(String name, int price) {
        this.name = name;
        this.price = price;
        this.comments = new ArrayList<Comment>();
    }

    public boolean addComment(String author, String text, int rating) {
        if (rating < 1 || rating > 5) {
            return false; // rating tidak valid
        }

        for (Comment comment : comments) {
            if (comment.getAuthor().equals(author)) {
                return false;
            }
        }

        Comment newComment = new Comment(author, text, rating);
        comments.add(newComment);
        return true;
    }

    public boolean removeComment(Comment comment) {
        return comments.remove(comment);
    }

    public int getNumberOfComments() {
        return comments.size();
    }

    public void showInfo() {
        System.out.println("=================================");
        System.out.println("Item: " + name);
        System.out.println("Price: " + price);
        System.out.println("Number of comments: " + getNumberOfComments());
        System.out.println("---------------------------------");

        for (Comment comment : comments) {
            comment.print();
            System.out.println();
        }
    }

    public Comment findMostHelpfulComment() {
        if (comments.isEmpty()) {
            return null;
        }

        Comment best = comments.get(0);
        for (Comment current : comments) {
            if (current.getVoteBalance() > best.getVoteBalance()) {
                best = current;
            }
        }
        return best;
    }
   
    //Method tambahan untuk testing
    public Comment getCommentByAuthor(String author) {
    for (Comment comment : comments) {
        if (comment.getAuthor().equals(author)) {
            return comment;
        }
    }
    return null;
    }

}

SalesItemTest

public class SalesItemTest {
    public static void main(String[] args) {
        SalesItem item = new SalesItem("Rice Cooker Serbaguna", 300000);

        item.addComment("Andi", "Nasinya jadi pulen dan enak", 5);
        item.addComment("Andi", "Mau nambahin review lain.", 4); //ga bisa karena author sama dengan sebelumnya
        item.addComment("Budi", "Kurang bagus", 6); //ga valid
        item.addComment("Citra", "Nasinya cepat basi jika disimpan agak lama", 3);

        System.out.println("\n=== Informasi Item ===");
        item.showInfo();
       
        Comment andiComment = item.getCommentByAuthor("Andi");
        if (andiComment != null) {
            System.out.println("Menambah upvote pada komentar Andi");
            andiComment.upvote();
            System.out.println("Menambah upvote pada komentar Andi");
            andiComment.upvote();
            System.out.println("Menambah downvote pada komentar Andi");
            andiComment.downvote();
        } else {
            System.out.println("Komentar Andi tidak ditemukan.");
        }
       
        System.out.println("");
       
         Comment citraComment = item.getCommentByAuthor("Citra");
        if (citraComment != null) {
            System.out.println("Menambah upvote pada komentar Citra");
            citraComment.upvote();
            System.out.println("Menambah upvote pada komentar Citra");
            citraComment.upvote();
            System.out.println("Menambah downvote pada komentar Citra");
            citraComment.downvote();
            System.out.println("Menambah downvote pada komentar Citra");
            citraComment.downvote();
        } else {
            System.out.println("Komentar Citra tidak ditemukan.");
        }

        System.out.println("\n=== Komentar Paling Membantu ===");
        Comment best = item.findMostHelpfulComment();
        if (best != null) {
            best.print();
        } else {
            System.out.println("Belum ada komentar.");
        }
    }
}

Comment

public class Comment {
    private String author;
    private String text;
    private int rating;
    private int upvotes;
    private int downvotes;

    public Comment(String author, String text, int rating) {
        this.author = author;
        this.text = text;
        this.rating = rating;
        this.upvotes = 0;
        this.downvotes = 0;
    }

    public String getAuthor() {
        return author;
    }

    public void upvote() {
        upvotes++;
    }

    public void downvote() {
        downvotes++;
    }

    public int getVoteBalance() {
        return upvotes - downvotes;
    }

    public void print() {
        System.out.println("Author: " + author);
        System.out.println("Rating: " + rating);
        System.out.println("Comment: " + text);
        System.out.println("Votes: " + getVoteBalance());
    }
}

Pertemuan 9 | World of Zuul

 Naufal Daffa Alfa Zain                                                                                                               5025241066                                                                                                                               Pemrograman Berorientasi Objek – A

Pada pertemuan kesembilan mata kuliah Pemrograman Berorientasi Objek (PBO A), kami diminta untuk membuat dan menjalankan proyek Game of Zuul menggunakan bahasa Java di platform BlueJ. Program ini merupakan permainan berbasis teks sederhana di mana pemain dapat berpindah-pindah ruangan menggunakan perintah tertentu seperti go, help, dan quit. Melalui proyek ini, mahasiswa dilatih untuk memahami hubungan antarobjek dalam sebuah sistem serta bagaimana setiap kelas saling berinteraksi untuk membentuk alur permainan yang utuh.

Secara garis besar, Game of Zuul terdiri dari beberapa kelas yang merepresentasikan elemen-elemen dalam permainan seperti ruang, perintah, pembacaan input pengguna, dan logika permainan itu sendiri. Ketika dijalankan, program menampilkan deskripsi lokasi pemain, arah keluarnya, serta merespons perintah yang dimasukkan melalui terminal. Pemain bisa berpindah ruangan sesuai arah yang tersedia, meminta bantuan untuk melihat daftar perintah, atau keluar dari permainan dengan mengetik quit.

Melalui latihan ini, kami belajar tentang penerapan prinsip dasar pemrograman berorientasi objek seperti enkapsulasi, komposisi, dan interaksi antarobjek. Setiap kelas memiliki tanggung jawab tersendiri dan saling berhubungan untuk membentuk alur kerja yang utuh. Selain itu, latihan ini juga membantu kami memahami pentingnya desain kelas yang kohesif dan memiliki low coupling agar program mudah dikembangkan dan dipelihara.

Secara keseluruhan, proyek Game of Zuul menjadi sarana pembelajaran yang efektif untuk memperdalam konsep OOP melalui studi kasus permainan sederhana yang interaktif dan aplikatif di BlueJ.

Sumber source code dapat dilihat di Sumber



Source code lengkap 

Game

public class Game
{
    private Parser parser;
    private Room currentRoom;
   
    // Constructor, create game, inisialisasi map (rooms)
    public Game() {
        createRooms();
        parser = new Parser();
    }
   
    // Create all rooms, and link exits
    private void createRooms() {
        Room outside, theater, pub, lab, office;
       
        //create rooms
        outside = new Room("outside the main entrance of the university");
        theater = new Room("in a lecture theater");
        pub = new Room("in the campus pub");
        lab = new Room("in a computing lab");
        office = new Room("in the computing admin office");
       
        //inisialisasi room exit
        outside.setExits(null, theater, lab, pub);
        theater.setExits(null, null, null, outside);
        pub.setExits(null, outside, null, null);
        lab.setExits(outside, office, null, null);
        office.setExits(null, null, null, lab);
       
        //set start point
        currentRoom = outside;
       
    }
   
    //play routine
    public void play() {
        printWelcome();
       
        //masuk main command loop.
        boolean finished = false;
        while(!finished) {
            Command command = parser.getCommand();
            finished = processCommand(command);
        }
       
        System.out.println("Thank you for playing. Good bye.");
    }
   
    //print welcome message
    private void printWelcome() {
        System.out.println();
        System.out.println("Welcome to the World of Zuul!");
        System.out.println("World of Zuul is a new, incredibly boring advanture game.");
        System.out.println("Type 'help' if you need help.");
        System.out.println();
        System.out.println("You are " + currentRoom.getDescription());
        System.out.print("Exits: ");
        if(currentRoom.northExit != null) System.out.print("north ");
        if(currentRoom.eastExit != null) System.out.print("east ");
        if(currentRoom.southExit != null) System.out.print("south ");
        if(currentRoom.westExit != null) System.out.print("west ");
        System.out.println();
       
    }
   
    private boolean processCommand(Command command) {
        boolean wantToQuit = false;
       
        if(command.isUnknown()) {
            System.out.println("I'm sorry, I don't know what you mean...");
            return false;
        }
       
        String commandWord = command.getCommandWord();
        if(commandWord.equals("help")) printHelp();
        else if(commandWord.equals("go")) goRoom(command);
        else if(commandWord.equals("quit")) wantToQuit = quit(command);
       
        return wantToQuit;
    }
   
    private void printHelp() {
        System.out.println("You are lost. You are alone.");
        System.out.println("You wander around at the campus.");
        System.out.println();
        System.out.println("Your command words are: ");
        System.out.println(" go quit help");
           
    }
   
    //try to go one direction
    private void goRoom(Command command) {
        if(!command.hasSecondWord()) {
            System.out.println("Go where?");
            System.out.println("'go <direction>'");
            return;
        }
       
        String direction = command.getSecondWord();
       
        //try to leave current room.
        Room nextRoom = null;
        if(direction.equals("north")) nextRoom = currentRoom.northExit;
        if(direction.equals("east")) nextRoom = currentRoom.eastExit;
        if(direction.equals("south")) nextRoom = currentRoom.southExit;
        if(direction.equals("west")) nextRoom = currentRoom.westExit;
       
        if(nextRoom == null) System.out.println("There is no door!");
        else {
            currentRoom = nextRoom;
            System.out.println("You are " + currentRoom.getDescription());
            System.out.print("Exits: ");
            if(currentRoom.northExit != null) System.out.print("north ");
            if(currentRoom.eastExit != null) System.out.print("east ");
            if(currentRoom.southExit != null) System.out.print("south ");
            if(currentRoom.westExit != null) System.out.print("west ");
            System.out.println();
       
        }
    }
   
    private boolean quit(Command command){
        if(command.hasSecondWord()) {
            System.out.println("Quit what?");
            return false;
        } else return true;
    }
}

Room

public class Room
{
    public String description;
    public Room northExit;
    public Room southExit;
    public Room eastExit;
    public Room westExit;

    public Room(String description)
    {
        this.description = description;
    }

    public void setExits(Room north, Room east, Room south, Room west)
    {
        if(north != null)
            northExit = north;
        if(east != null)
            eastExit = east;
        if(south != null)
            southExit = south;
        if(west != null)
            westExit = west;
    }

    /**
     * @return The description of the room.
     */
    public String getDescription()
    {
        return description;
    }

}

Command

public class Command
{
    private String commandWord;
    private String secondWord;

    public Command(String firstWord, String secondWord)
    {
        commandWord = firstWord;
        this.secondWord = secondWord;
    }

    public String getCommandWord()
    {
        return commandWord;
    }

    public String getSecondWord()
    {
        return secondWord;
    }

    public boolean isUnknown()
    {
        return (commandWord == null);
    }

    public boolean hasSecondWord()
    {
        return (secondWord != null);
    }
}

Parser

import java.util.Scanner;

public class Parser
{
    private CommandWords commands;  // holds all valid command words
    private Scanner reader;         // source of command input

    public Parser()
    {
        commands = new CommandWords();
        reader = new Scanner(System.in);
    }

    public Command getCommand()
    {
        String inputLine;   // will hold the full input line
        String word1 = null;
        String word2 = null;

        System.out.print("> ");     // print prompt

        inputLine = reader.nextLine();

        // Find up to two words on the line.
        Scanner tokenizer = new Scanner(inputLine);
        if(tokenizer.hasNext()) {
            word1 = tokenizer.next();      // get first word
            if(tokenizer.hasNext()) {
                word2 = tokenizer.next();      // get second word
                // note: we just ignore the rest of the input line.
            }
        }

        if(commands.isCommand(word1)) {
            return new Command(word1, word2);
        }
        else {
            return new Command(null, word2);
        }
    }
}

CommandWords

public class CommandWords
{
    // a constant array that holds all valid command words
    private static final String[] validCommands = {
        "go", "quit", "help"
    };

    /**
     * Constructor - initialise the command words.
     */
    public CommandWords()
    {
        // nothing to do at the moment...
    }

    public boolean isCommand(String aString)
    {
        for(int i = 0; i < validCommands.length; i++) {
            if(validCommands[i].equals(aString))
                return true;
        }
        // if we get here, the string was not found in the commands
        return false;
    }
}

Pertemuan 13 | Abstract Class

 Nama     : Naufal Daffa Alfa Zain  Nrp         : 5025241066  Kelas      : Pemrograman Web A2 Pada pertemuan ke‑13 kami mendapat dua tugas. ...