public class OrderTest {
public static void main(String[] args) {
Order order1 = new Order("Fried Rice", 2, 17);
Order order2 = new Order("Fanta", 4, 6);
System.out.println("Order #1\n" + order1);
System.out.println("Order #2\n" + order2);
// try: remove method toString() and see what happends
}
}
class Order {
private String name;
private int amount;
private double unitPrice;
public Order(String n, int num, double price) {
if(n == null || num < 0 || price < 0)
throw new RuntimeException(“program error”);
name = n;
amount = num;
unitPrice = price;
}
public String toString() {
String str;
double total;
total = amount * unitPrice;
str = "Item name : " + name + "\n" +
"Amount : " + amount + " unit(s)\n" +
"Unit price : " + unitPrice + " baht\n" +
"Total price : " + total + " baht\n";
return(str);
}
}
OrderTest.java output
Order #1
Item name : Fried Rice
Amount : 2 unit(s)
Unit price : 17.0 baht
Total price : 34.0 baht
Order #2
Item name : Fanta
Amount : 4 unit(s)
Unit price : 6.0 baht
Total price : 24.0 baht
Tag: Study Code Program Java
No comments:
Post a Comment