Implementasi Class dan Object studi kasus Ticket Machine
TicketMachine.java
-
public class
TicketMachine
-
{
-
private int
price
;
-
private int
balance
;
-
private int
total
;
-
-
public
TicketMachine
(
int
cost
)
-
{
-
price = cost;
-
balance = 0;
-
total = 0;
-
}
-
public int
getPrice()
-
{
-
return price;
-
}
-
public int
getBalance()
-
{
-
return balance;
-
}
-
public
void
insertMoney
(
int
amount
)
-
{
-
if (amount
> 0)
-
{
-
balance = balance + amount;
-
}
-
else
-
{
-
System.out.println (
"Use a positive amount rather than: " + amount);
-
}
-
}
-
public
void
printTicket
()
-
{
-
if (balance
>= price)
-
{
-
System.out.println (
"##################");
-
System.out.println (
"# The BlueJ Line");
-
System.out.println (
"# Ticket");
-
System.out.println (
"# " + price + " cents.");
-
System.out.println (
"##################");
-
System.out.println
();
-
total = total + price;
-
balance = balance - amount;
-
}
-
else
-
{
-
System.out.println (
"You must insert at least: " + (price - balance) + "
cents.");
-
}
-
}
-
public int
refundBalance()
-
{
-
int amountToRefund
;
-
amountToRefund = balance;
-
balance = 0;
-
return amountToRefund;
-
}
-
}
TicketMachine.java
-
import
java.until.Scanner
;
-
public class
IntMain
-
{
-
public static
void
main
(
String args
[])
-
{
-
Scanner scan = new Scanner(System.in);
-
int cost, menu, balance;
-
System.out.println("Masukkan harga tiket \n");
-
cost=scan.nextInt();
-
TicketMachine ticket=new TicketMachine(cost);
-
System.out.println("1. Get Price");
-
System.out.println("2. Get Balance");
-
System.out.println("3. Insert Money");
-
System.out.println("4. Print Ticket");
-
int flag=1;
-
while(flag==1)
-
{
-
menu=scan.nextInt();
-
switch(menu)
-
{
-
case 1:
-
cost=ticket.getPrice();
-
System.out.println(cost);
-
break;
-
case 2:
-
balance=ticket.getBalance();
-
System.out.println(balance);
-
break;
-
case 3:
-
int money=scan.nextInt();
-
ticket.insertMoney(money);
-
break;
-
case 4:
-
ticket.printTicket();
-
flag=0;
-
break;
-
}
-
}
-
}
-
}
Hasil keluaran dari program di atas sebagai berikut :
Komentar
Posting Komentar