1. Program untuk class ticket machine
public class TicketMachine{
private int price; //harga tiket
private int balance; //uang yang dimasukkan saat transaksi oleh 1 orang
private int total; //uang ada yang ada dlm machine
private int tickets; //tiket yang dibeli dlm 1 transaksi
public TicketMachine(){
price = 500;
balance = 0;
total = 0;
tickets = 0;
}
public TicketMachine(int cost){
price = cost;
balance = 0;
total = 0;
tickets = 0;
}
public int getPrice(){
return price;
}
public int getBalance(){
return balance;
}
public int getTotal(){
return total;
}
public void insertMoney(int amount){
balance = balance + amount;
}
public void buyTicket(){
if(price>balance){
System.out.println("Not enough balance entered to buy ticket. Please add more.");
}
else{
while(balance>price){
balance -= price;
total += price;
tickets++;
}
}
}
public void printTicket(){
if(tickets == 0){
System.out.println("You haven't bought any tickets");
}
else{
System.out.println("You bought " + tickets + " of these:");
System.out.println("+------------------------+");
System.out.println("| The BlueJ Line Ticket.");
System.out.println("| " + price + " cents.");
System.out.println("+------------------------+");
}
}
public void endTransaction(){
System.out.println("Thank you for your purchase!");
System.out.println("Your change is " + balance + " cents");
balance = 0;
tickets = 0;
}
}
2. Program untuk eksekusi
import java.util.Scanner;
public class ticketMachine1{
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
int cost,menu;
System.out.println("Masukkan harga tiket");
cost = scan.nextInt();
TicketMachine mesin = new TicketMachine(cost);
boolean exit = false;
while(exit == false){
System.out.println("Price : " + mesin.getPrice());
System.out.println("Balance : " + mesin.getBalance());
System.out.println("--=Instructions=--");
System.out.println("1. Insert Money");
System.out.println("2. Buy Ticket");
System.out.println("3. Print Ticket");
System.out.println("4. End Transaction");
System.out.println("5. Exit");
menu = scan.nextInt();
switch(menu){
case 1:
System.out.println("Insert Amount:");
int money = scan.nextInt();
mesin.insertMoney(money);
break;
case 2:
mesin.buyTicket();
break;
case 3:
mesin.printTicket();
break;
case 4:
mesin.endTransaction();
break;
case 5:
exit = true;
break;
default:
System.out.println("Instruction Unknown");
break;
}
if(exit==true){
System.out.println("You have collected "+mesin.getTotal()+" cents from this machine");
}
}
}
}
Comments
Post a Comment