תכנות מתקדם ב-Java/אובייקטים: הבדלים בין גרסאות בדף
תוכן שנמחק תוכן שנוסף
Johnny Zoo (שיחה | תרומות) מ בעבודה |
Johnny Zoo (שיחה | תרומות) אין תקציר עריכה |
||
שורה 61:
===תוכנית המכולת===
נראה כאן מימוש בג'אווה של ה"מכולת" אותה תיארנו קודם. נעבוד עם
<source lang = "java">
// Item.java
שורה 68:
// Item's name
private String _name;
// Item's description
private String _description;
// Item's price
private double _price;
// Quantity of that item
private int _quantity;
// Days left for that item until expired
private int _daysLeft;
/*
שורה 97:
public void setQuantity(int newQuantity) {
_quantity = newQuantity;
}▼
// Get item's name
public String getName() {
}
שורה 102 ⟵ 107:
public double getPrice() {
return _price;
}
// Get item's quantity
public int getQuantity() {
}
שורה 119 ⟵ 129:
public class Stock {
// Array that holds all items in the stock
private Item
private Item _item2;
/*
שורה 129 ⟵ 138:
*/
public Stock() {
_item1 = null;
// Build the array of items▼
_item2 = null;
}
// Add item to stock
public void addItem(Item it
if(
_item1 = it;
System.out.println("Cannot add item: this cell is full");▼
▲ return;
_item2 = it;
else
System.out.println("Stock is full, cannot add "+it.getName());
}
// Print all items in stock
public void printStock() {
if(_item1 != null) _item1.printItem();
}
שורה 153 ⟵ 161:
public double sumStock() {
double sum = 0.0;
sum+=_item1.getPrice()*_item1.getQuantity();
▲ if(_stock[i] != null)
if(_item2 != null)
sum+=_item2.getPrice()*_item2.getQuantity();
return sum;
}
// Set new quantity for that item
public void setItemQuantity(
if(_item1.getName().equals(itemName))
▲ if(_stock[serial] == null) {
else if(_item2.getName().equals(itemName))
▲ return;
_item2.setQuantity(newQuantity);
else {
}
▲ _stock[serial].setQuantity(newQuantity);
}
}
</source>
הקלה נוספת לשם הפשטות: המלאי יכול להכיל רק עד שני מוצרים. זהו, כמובן, מימוש לא שימושי במיוחד, והוא נעשה לצרכי הדגמה בלבד. נראה כאן את המחלקה Grocery, שתשתמש במחלקות שיצרנו על מנת לנהל את המלאי:
<source lang = "java">
// Grocery.java
public class Grocery {
public static void main(String[] args) {
Stock stck = new Stock();
// Print the stock - it is empty now
stck.printStock();
// Add items to stock:
Item it1 = new Item("Cheese","Smelly green cheese", 1.5, 2, 7);
Item it2 = new Item("Tomato","Fresh tomamto", 2.6, 25, 10);
stck.addItem(it1);
stck.addItem(it2);
stck.printStock();
System.out.println("Total price of stock: " + stck.sumStock());
// Try to insert third item to stock:
Item it3 = new Item("New item","",0.0,0,0);
stck.addItem(it3);
// Change quantity of cheese:
stck.setItemQuantity("Cheese", 200);
// Change quantity of item that does not exist:
stck.setItemQuantity("Bread", 1000);
System.out.println("Now total price of stock is "+stck.sumStock());
}
}
</source>
|