15 Oktober 2018

UTS PBO B

Berikut adalah jawaban dari soal Ujian Tengah Semester PBO B nomor 5, yaitu:

"Implementasikan program simulasinya (Buat komentar di blog untuk link solusinya)"

Dibutuhkan 2 class, yaitu: class DispenserBox dan class ThermalPrinter. Berikut source codenya.

1. DispenserBox


 import java.util.Scanner;  
 /**  
  * Kinerja dispenser box.  
  *  
  * @author (Mohammad Nafis Naufally/05111640000038)  
  * @version (1/20181015)  
  */  
 public class DispenserBox   
 {   
   public static void main(String args[])   
   {   
     Scanner scan= new Scanner(System.in);   
     int i=0;  
     int menu;  
       
     System.out.println("SELAMAT DATANG \n");  
     System.out.println("MASUKKAN PLAT NOMOR ANDA");   
       
     String plat = scan.nextLine();  
       
     System.out.println("PLAT ANDA: " + plat);  
           
     ThermalPrinter karcis=new ThermalPrinter(plat);  
     menu = 0;  
     while(menu!=2)  
     {  
       System.out.println("");  
       System.out.println("PILIH TINDAKAN:");  
       System.out.println("1. CETAK KARCIS");   
       System.out.println("2. EXIT");   
         
       menu=scan.nextInt();   
       switch(menu)   
       {    
         case 1:   
         karcis.printKarcis();   
         break;   
         case 2:  
         System.out.println("TERIMA KASIH");  
         break;  
       }   
     }  
   }   
 }  

2. ThermalPrinter


   
 /**  
  * Pekerjaan thermal printer.  
  *  
  * @author (Mohammad Nafis Naufally/05111640000038)  
  * @version (1/20181015)  
  */  
 public class ThermalPrinter  
 {  
    private String nomor;    
    public ThermalPrinter(String platnomor)   
    {   
      nomor = platnomor;   
    }  
    public void printKarcis()   
    {   
      // Simulate the printing of a ticket.   
        System.out.println("##################");   
        System.out.println("# TIKET MASUK  #");   
        System.out.println("#   UNTUK   #");   
        System.out.println("#  " + nomor + "  #");   
        System.out.println("##################");   
        System.out.println();  
    }   
 }   


Kemudian jalankan fungsi pada class DispenserBox sesuai petunjuk. Berikut ini adalah screenshot program tersebut.


Demikian jawaban dari soal UTS nomor 5. Terima kasih atas kunjungannya.




Jangan lupa, semangat ketik 10 jari. :)

9 Oktober 2018

Tugas 5 & 6 PBO B

Halo, pada kesempatan kali ini saya akan membahas 2 topik, yaitu cara membuat project music organizer dan project sistem lelang sekaligus menggunakan bahasa pemrograman Java.

1. Music Organizer

Pertama-tama buatlah folder "audio" yang berlokasi sama dengan folder project BlueJ, dan isilah dengan sample music yang berjudul sama dan juga sesuai dengan program yang akan dibuat berikut ini.

Diperlukan 4 class yaitu: class MusicOrganizer, TrackReader, MusicPlayer, dan Track

a. MusicOrganizer


 import java.util.ArrayList;  
   
 /**  
  * A class to hold details of audio tracks.  
  * Individual tracks may be played.  
  *   
  * @author (Mohammad Nafis Naufally/05111640000038)  
  * @version (1/20181009)  
  */  
 public class MusicOrganizer  
 {  
   // An ArrayList for storing music tracks.  
   private ArrayList<Track> tracks;  
   // A player for the music tracks.  
   private MusicPlayer player;  
   // A reader that can read music files and load them as tracks.  
   private TrackReader reader;  
   
   /**  
    * Create a MusicOrganizer  
    */  
   public MusicOrganizer()  
   {  
     tracks = new ArrayList<>();  
     player = new MusicPlayer();  
     reader = new TrackReader();  
     readLibrary("../audio");  
     System.out.println("Music library loaded. " + getNumberOfTracks() + " tracks.");  
     System.out.println();  
   }  
     
   /**  
    * Add a track file to the collection.  
    * @param filename The file name of the track to be added.  
    */  
   public void addFile(String filename)  
   {  
     tracks.add(new Track(filename));  
   }  
     
   /**  
    * Add a track to the collection.  
    * @param track The track to be added.  
    */  
   public void addTrack(Track track)  
   {  
     tracks.add(track);  
   }  
     
   /**  
    * Play a track in the collection.  
    * @param index The index of the track to be played.  
    */  
   public void playTrack(int index)  
   {  
     if(indexValid(index)) {  
       Track track = tracks.get(index);  
       player.startPlaying(track.getFilename());  
       System.out.println("Now playing: " + track.getArtist() + " - " + track.getTitle());  
     }  
   }  
     
   /**  
    * Return the number of tracks in the collection.  
    * @return The number of tracks in the collection.  
    */  
   public int getNumberOfTracks()  
   {  
     return tracks.size();  
   }  
     
   /**  
    * List a track from the collection.  
    * @param index The index of the track to be listed.  
    */  
   public void listTrack(int index)  
   {  
     System.out.print("Track " + index + ": ");  
     Track track = tracks.get(index);  
     System.out.println(track.getDetails());  
   }  
     
   /**  
    * Show a list of all the tracks in the collection.  
    */  
   public void listAllTracks()  
   {  
     System.out.println("Track listing: ");  
   
     for(Track track : tracks) {  
       System.out.println(track.getDetails());  
     }  
     System.out.println();  
   }  
     
   /**  
    * List all tracks by the given artist.  
    * @param artist The artist's name.  
    */  
   public void listByArtist(String artist)  
   {  
     for(Track track : tracks) {  
       if(track.getArtist().contains(artist)) {  
         System.out.println(track.getDetails());  
       }  
     }  
   }  
     
   /**  
    * Remove a track from the collection.  
    * @param index The index of the track to be removed.  
    */  
   public void removeTrack(int index)  
   {  
     if(indexValid(index)) {  
       tracks.remove(index);  
     }  
   }  
     
   /**  
    * Play the first track in the collection, if there is one.  
    */  
   public void playFirst()  
   {  
     if(tracks.size() > 0) {  
       player.startPlaying(tracks.get(0).getFilename());  
     }  
   }  
     
   /**  
    * Stop the player.  
    */  
   public void stopPlaying()  
   {  
     player.stop();  
   }  
   
   /**  
    * Determine whether the given index is valid for the collection.  
    * Print an error message if it is not.  
    * @param index The index to be checked.  
    * @return true if the index is valid, false otherwise.  
    */  
   private boolean indexValid(int index)  
   {  
     // The return value.  
     // Set according to whether the index is valid or not.  
     boolean valid;  
       
     if(index < 0) {  
       System.out.println("Index cannot be negative: " + index);  
       valid = false;  
     }  
     else if(index >= tracks.size()) {  
       System.out.println("Index is too large: " + index);  
       valid = false;  
     }  
     else {  
       valid = true;  
     }  
     return valid;  
   }  
     
   private void readLibrary(String folderName)  
   {  
     ArrayList<Track> tempTracks = reader.readTracks(folderName, ".mp3");  
   
     // Put all thetracks into the organizer.  
     for(Track track : tempTracks) {  
       addTrack(track);  
     }  
   }  
 }  
   


2. TrackReader

 import java.io.File;  
 import java.io.FilenameFilter;  
 import java.io.IOException;  
 import java.util.ArrayList;  
 import java.util.Arrays;  
 import java.util.stream.Collectors;  
   
 /**  
  * A helper class for our music application. This class can read files from the file system  
  * from a given folder with a specified suffix. It will interpret the file name as artist/  
  * track title information.  
  *   
  * It is expected that file names of music tracks follow a standard format of artist name  
  * and track name, separated by a dash. For example: TheBeatles-HereComesTheSun.mp3  
  *   
  * @author (Mohammad Nafis Naufally/05111640000038)  
  * @version (1/20181009)  
  */  
 public class TrackReader  
 {  
   /**  
    * Create the track reader, ready to read tracks from the music library folder.  
    */  
   public TrackReader()  
   {  
     // Nothing to do here.  
   }  
     
   /**  
    * Read music files from the given library folder  
    * with the given suffix.  
    * @param folder The folder to look for files.  
    * @param suffix The suffix of the audio type.  
    */  
   public ArrayList<Track> readTracks(String folder, String suffix)  
   {  
     File audioFolder = new File(folder);  
     File[] audioFiles = audioFolder.listFiles((dir, name) ->   
           name.toLowerCase().endsWith(suffix));  
       
     // Put all the matching files into the organizer.  
     ArrayList<Track> tracks =   
       Arrays.stream(audioFiles).  
           map(file -> decodeDetails(file)).  
           collect(Collectors.toCollection(ArrayList::new));  
     return tracks;  
   }  
   
   /**  
    * Try to decode details of the artist and the title  
    * from the file name.  
    * It is assumed that the details are in the form:  
    *   artist-title.mp3  
    * @param file The track file.  
    * @return A Track containing the details.  
    */  
   private Track decodeDetails(File file)  
   {  
     // The information needed.  
     String artist = "unknown";  
     String title = "unknown";  
     String filename = file.getPath();  
       
     // Look for artist and title in the name of the file.  
     String details = file.getName();  
     String[] parts = details.split("-");  
       
     if(parts.length == 2) {  
       artist = parts[0];  
       String titlePart = parts[1];  
       // Remove a file-type suffix.  
       parts = titlePart.split("\\.");  
       if(parts.length >= 1) {  
         title = parts[0];  
       }  
       else {  
         title = titlePart;  
       }  
     }  
     return new Track(artist, title, filename);  
   }  
 }  
   

3. MusicPlayer


 import java.io.BufferedInputStream;  
 import java.io.FileInputStream;  
 import java.io.InputStream;  
 import java.io.IOException;  
 import javazoom.jl.decoder.JavaLayerException;  
 import javazoom.jl.player.AudioDevice;  
 import javazoom.jl.player.FactoryRegistry;  
 import javazoom.jl.player.advanced.AdvancedPlayer;  
   
 /**  
  * Provide basic playing of MP3 files via the javazoom library.  
  * See http://www.javazoom.net/  
  *   
  * @author (Mohammad Nafis Naufally/05111640000038)  
  * @version (1/20181009)  
  */  
 public class MusicPlayer  
 {  
   // The current player. It might be null.  
   private AdvancedPlayer player;  
     
   /**  
    * Constructor for objects of class MusicFilePlayer  
    */  
   public MusicPlayer()  
   {  
     player = null;  
   }  
     
   /**  
    * Play a part of the given file.  
    * The method returns once it has finished playing.  
    * @param filename The file to be played.  
    */  
   public void playSample(String filename)  
   {  
     try {  
       setupPlayer(filename);  
       player.play(500);  
     }  
     catch(JavaLayerException e) {  
       reportProblem(filename);  
     }  
     finally {  
       killPlayer();  
     }  
   }  
     
   /**  
    * Start playing the given audio file.  
    * The method returns once the playing has been started.  
    * @param filename The file to be played.  
    */  
   public void startPlaying(final String filename)  
   {  
     try {  
       setupPlayer(filename);  
       Thread playerThread = new Thread() {  
         public void run()  
         {  
           try {  
             player.play(5000);  
           }  
           catch(JavaLayerException e) {  
             reportProblem(filename);  
           }  
           finally {  
             killPlayer();  
           }  
         }  
       };  
       playerThread.start();  
     }  
     catch (Exception ex) {  
       reportProblem(filename);  
     }  
   }  
     
   public void stop()  
   {  
     killPlayer();  
   }  
     
   /**  
    * Set up the player ready to play the given file.  
    * @param filename The name of the file to play.  
    */  
   private void setupPlayer(String filename)  
   {  
     try {  
       InputStream is = getInputStream(filename);  
       player = new AdvancedPlayer(is, createAudioDevice());  
     }  
     catch (IOException e) {  
       reportProblem(filename);  
       killPlayer();  
     }  
     catch(JavaLayerException e) {  
       reportProblem(filename);  
       killPlayer();  
     }  
   }  
   
   /**  
    * Return an InputStream for the given file.  
    * @param filename The file to be opened.  
    * @throws IOException If the file cannot be opened.  
    * @return An input stream for the file.  
    */  
   private InputStream getInputStream(String filename)  
     throws IOException  
   {  
     return new BufferedInputStream(  
           new FileInputStream(filename));  
   }  
   
   /**  
    * Create an audio device.  
    * @throws JavaLayerException if the device cannot be created.  
    * @return An audio device.  
    */  
   private AudioDevice createAudioDevice()  
     throws JavaLayerException  
   {  
     return FactoryRegistry.systemRegistry().createAudioDevice();  
   }  
   
   /**  
    * Terminate the player, if there is one.  
    */  
   private void killPlayer()  
   {  
     synchronized(this) {  
       if(player != null) {  
         player.stop();  
         player = null;  
       }  
     }  
   }  
     
   /**  
    * Report a problem playing the given file.  
    * @param filename The file being played.  
    */  
   private void reportProblem(String filename)  
   {  
     System.out.println("There was a problem playing: " + filename);  
   }  
   
 }  
   

4. Track


 /**  
  * Store the details of a music track,  
  * such as the artist, title, and file name.  
  *   
  * @author (Mohammad Nafis Naufally/05111640000038)  
  * @version (1/20181009)  
  */  
 public class Track  
 {  
   // The artist.  
   private String artist;  
   // The track's title.  
   private String title;  
   // Where the track is stored.  
   private String filename;  
     
   /**  
    * Constructor for objects of class Track.  
    * @param artist The track's artist.  
    * @param title The track's title.  
    * @param filename The track file.   
    */  
   public Track(String artist, String title, String filename)  
   {  
     setDetails(artist, title, filename);  
   }  
     
   /**  
    * Constructor for objects of class Track.  
    * It is assumed that the file name cannot be  
    * decoded to extract artist and title details.  
    * @param filename The track file.   
    */  
   public Track(String filename)  
   {  
     setDetails("unknown", "unknown", filename);  
   }  
     
   /**  
    * Return the artist.  
    * @return The artist.  
    */  
   public String getArtist()  
   {  
     return artist;  
   }  
     
   /**  
    * Return the title.  
    * @return The title.  
    */  
   public String getTitle()  
   {  
     return title;  
   }  
     
   /**  
    * Return the file name.  
    * @return The file name.  
    */  
   public String getFilename()  
   {  
     return filename;  
   }  
       
   /**  
    * Return details of the track: artist, title and file name.  
    * @return The track's details.  
    */  
   public String getDetails()  
   {  
     return artist + ": " + title + " (file: " + filename + ")";  
   }  
     
   /**  
    * Set details of the track.  
    * @param artist The track's artist.  
    * @param title The track's title.  
    * @param filename The track file.   
    */  
   private void setDetails(String artist, String title, String filename)  
   {  
     this.artist = artist;  
     this.title = title;  
     this.filename = filename;  
   }  
     
 }  
   



Hasilnya bisa dilihat lewat dokumentasi berikut:



2. Auction

Diperlukan 4 class yaitu: class Auction, Bid, Lot, dan Person.

a. Auction


 import java.util.ArrayList;  
   
 /**  
  * A simple model of an auction.  
  * The auction maintains a list of lots of arbitrary length.  
  *  
  * @author (Mohammad Nafis Naufally/05111640000038)  
  * @version (1/20181009)  
  */  
 public class Auction  
 {  
   // The list of Lots in this auction.  
   private ArrayList<Lot> lots;  
   // The number that will be given to the next lot entered  
   // into this auction.  
   private int nextLotNumber;  
   
   /**  
    * Create a new auction.  
    */  
   public Auction()  
   {  
     lots = new ArrayList<>();  
     nextLotNumber = 1;  
   }  
   
   /**  
    * Enter a new lot into the auction.  
    * @param description A description of the lot.  
    */  
   public void enterLot(String description)  
   {  
     lots.add(new Lot(nextLotNumber, description));  
     nextLotNumber++;  
   }  
   
   /**  
    * Show the full list of lots in this auction.  
    */  
   public void showLots()  
   {  
     for(Lot lot : lots) {  
       System.out.println(lot.toString());  
     }  
   }  
     
   /**  
    * Make a bid for a lot.  
    * A message is printed indicating whether the bid is  
    * successful or not.  
    *   
    * @param lotNumber The lot being bid for.  
    * @param bidder The person bidding for the lot.  
    * @param value The value of the bid.  
    */  
   public void makeABid(int lotNumber, Person bidder, long value)  
   {  
     Lot selectedLot = getLot(lotNumber);  
     if(selectedLot != null) {  
       Bid bid = new Bid(bidder, value);  
       boolean successful = selectedLot.bidFor(bid);  
       if(successful) {  
         System.out.println("The bid for lot number " +  
                   lotNumber + " was successful.");  
       }  
       else {  
         // Report which bid is higher.  
         Bid highestBid = selectedLot.getHighestBid();  
         System.out.println("Lot number: " + lotNumber +  
                   " already has a bid of: " +  
                   highestBid.getValue());  
       }  
     }  
   }  
   
   /**  
    * Return the lot with the given number. Return null  
    * if a lot with this number does not exist.  
    * @param lotNumber The number of the lot to return.  
    */  
   public Lot getLot(int lotNumber)  
   {  
     if((lotNumber >= 1) && (lotNumber < nextLotNumber)) {  
       // The number seems to be reasonable.  
       Lot selectedLot = lots.get(lotNumber - 1);  
       // Include a confidence check to be sure we have the  
       // right lot.  
       if(selectedLot.getNumber() != lotNumber) {  
         System.out.println("Internal error: Lot number " +  
                   selectedLot.getNumber() +  
                   " was returned instead of " +  
                   lotNumber);  
         // Don't return an invalid lot.  
         selectedLot = null;  
       }  
       return selectedLot;  
     }  
     else {  
       System.out.println("Lot number: " + lotNumber +  
                 " does not exist.");  
       return null;  
     }  
   }  
 }  
   

b. Bid


 /**  
  * A class that models an auction bid.  
  * It contains a reference to the Person bidding and the amount bid.  
  *   
  * @author (Mohammad Nafis Naufally/05111640000038)  
  * @version (1/20181009)  
  */  
 public class Bid  
 {  
   // The person making the bid.  
   private final Person bidder;  
   // The value of the bid. This could be a large number so  
   // the long type has been used.  
   private final long value;  
   
   /**  
    * Create a bid.  
    * @param bidder Who is bidding for the lot.  
    * @param value The value of the bid.  
    */  
   public Bid(Person bidder, long value)  
   {  
     this.bidder = bidder;  
     this.value = value;  
   }  
   
   /**  
    * @return The bidder.  
    */  
   public Person getBidder()  
   {  
     return bidder;  
   }  
   
   /**  
    * @return The value of the bid.  
    */  
   public long getValue()  
   {  
     return value;  
   }  
 }  
   

c. Lot


 /**  
  * A class to model an item (or set of items) in an  
  * auction: a lot.  
  *   
  * @author (Mohammad Nafis Naufally/05111640000038)  
  * @version (1/20181009)  
  */  
 public class Lot  
 {  
   // A unique identifying number.  
   private final int number;  
   // A description of the lot.  
   private String description;  
   // The current highest bid for this lot.  
   private Bid highestBid;  
   
   /**  
    * Construct a Lot, setting its number and description.  
    * @param number The lot number.  
    * @param description A description of this lot.  
    */  
   public Lot(int number, String description)  
   {  
     this.number = number;  
     this.description = description;  
     this.highestBid = null;  
   }  
   
   /**  
    * Attempt to bid for this lot. A successful bid  
    * must have a value higher than any existing bid.  
    * @param bid A new bid.  
    * @return true if successful, false otherwise  
    */  
   public boolean bidFor(Bid bid)  
   {  
     if(highestBid == null) {  
       // There is no previous bid.  
       highestBid = bid;  
       return true;  
     }  
     else if(bid.getValue() > highestBid.getValue()) {  
       // The bid is better than the previous one.  
       highestBid = bid;  
       return true;  
     }  
     else {  
       // The bid is not better.  
       return false;  
     }  
   }  
     
   /**  
    * @return A string representation of this lot's details.  
    */  
   public String toString()  
   {  
     String details = number + ": " + description;  
     if(highestBid != null) {  
       details += "  Bid: " +   
             highestBid.getValue();  
     }  
     else {  
       details += "  (No bid)";  
     }  
     return details;  
   }  
   
   /**  
    * @return The lot's number.  
    */  
   public int getNumber()  
   {  
     return number;  
   }  
   
   /**  
    * @return The lot's description.  
    */  
   public String getDescription()  
   {  
     return description;  
   }  
   
   /**  
    * @return The highest bid for this lot.  
    *     This could be null if there is  
    *     no current bid.  
    */  
   public Bid getHighestBid()  
   {  
     return highestBid;  
   }  
 }  
   

d. Person

 /**  
  * Maintain details of someone who participates in an auction.  
  * @author (Mohammad Nafis Naufally/05111640000038)  
  * @version (1/20181009)  
  */  
 public class Person  
 {  
   // The name of this person.  
   private final String name;  
   
   /**  
    * Create a new person with the given name.  
    * @param name The person's name.  
    */  
   public Person(String name)  
   {  
     this.name = name;  
   }  
   
   /**  
    * @return The person's name.  
    */  
   public String getName()  
   {  
     return name;  
   }  
 }  
   


Kemudian compile source code di atas dan coba jalankan fungsi yang ada.

Terima kasih atas kunjungannya.




Jangan lupa, semangat ketik 10 jari. :)

1 Oktober 2018

Tugas 4 PBO B

Hari ini saya akan mencoba membuat jam digital secara real time dengan menggunakan bahasa Java.

Hanya ada 2 class yang diperlukan yaitu class Executor dan class clock.

Berikut ini source code-nya:

1. Executor

 /**   
  * Source Code Number Display   
  *   
  * @author (Mohammad Nafis Naufally/05111640000038)   
  * @version (1/20181001)   
  */  
 public class Executor {      
   public static void main(String[]args) {   
     new Executor();   
   }   
   public Executor() {   
     new clock();   
   }   
  }  

2. clock


 import javax.swing.*;   
 import java.awt.*;   
 import java.awt.event.*;   
 import java.util.Calendar;   
 /**   
  * Source Code Number Display   
  *   
  * @author (Mohammad Nafis Naufally/05111640000038)   
  * @version (1/20181001)   
  */   
 public class clock extends JFrame {   
   private static final long serialVersionUID = 1L;   
   // components   
   JTextField timeF;   
   JPanel panel;   
   public clock() {   
     // housekeeping   
     super("Java Digital Clock");   
     setSize(225,200);   
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
     setVisible(true);   
     setResizable(true);// for now   
     setLocationRelativeTo(null);   
       
     //init panel   
     panel = new JPanel();   
     panel.setLayout(new FlowLayout());   
       
     //init text field   
     timeF = new JTextField(10);   
     timeF.setEditable(false);   
     timeF.setFont(new Font("Arial",Font.BOLD,48));   
     panel.add(timeF);   
     add(panel);   
     Timer t = new Timer(1000, new Listener());   
     t.start();   
   }   
   class Listener implements ActionListener {   
     public void actionPerformed(ActionEvent e) {   
       Calendar rightNow = Calendar.getInstance();   
       int hour = rightNow.get(Calendar.HOUR_OF_DAY);   
       int min = rightNow.get(Calendar.MINUTE);   
       int sec = rightNow.get(Calendar.SECOND);   
       timeF.setText(hour+":"+min+":"+sec);   
     }   
   }   
 }  

Setelah di-compile, jalankan fungsi pada class Executor, dan hasilnya akan seperti dokumentasi berikut:


Demikian cara membuat jam digital real time. Terima kasih atas kunjungannya.



Jangan lupa, semangat ketik 10 jari. :)