This commit is contained in:
Luca Conte 2023-03-29 23:31:05 +02:00
parent 8240e68ed0
commit 9e54056f89
3 changed files with 109 additions and 0 deletions

View File

@ -0,0 +1,48 @@
package com.mymart;
/**
* Klasse zum abspeichern eines Artikels
* @author p8q-yhw-u1
*/
public class CartItem {
private String name;
private int quantity;
private double pricePerUnit;
/**
* initialisiert einen einzukaufenden Artikel mit den gegebenen Daten
* @param name der Name des Artikels
* @param quantity die Anzahl der gekauften Artikel
* @param pricePerUnit der Preis pro Artikel
*/
public CartItem(String name, int quantity, double pricePerUnit) {
this.name = name;
setQuantity(quantity);
this.pricePerUnit = pricePerUnit;
}
/**
* Liefert den Gesamtpreis des Artikels.
*/
public double getCost() {
return this.quantity * this.pricePerUnit;
}
/**
* Setzt die Anzahl der Artikel
* @param quantity Anzahl der Artikel (muss mindestens 1 sein)
*/
public void setQuantity(int quantity) {
if (quantity <= 0) {
throw new IllegalArgumentException("Die Anzahl (quantity) eines Artikels muss stehts >= 1 sein");
}
this.quantity = quantity;
}
/**
* Gibt das Item in String Form zurück.
*/
public String toString() {
return String.format("%3d x %-30s %10.2f %10.2f%n", this.quantity, this.name, this.pricePerUnit, this.getCost());
}
}

View File

@ -0,0 +1,50 @@
package com.mymart;
import java.util.ArrayList;
/**
* Klasse zum abspeichern eines Einkaufswagens mit inhalt
* @author p8q-yhw-u1
*/
public class ShoppingCart {
private ArrayList<CartItem> items;
/**
* initialisiert einen leeren Einkaufswagen
*/
public ShoppingCart() {
this.items = new ArrayList<CartItem>();
}
/**
* Fügt einen Artikel hinzu
* @param item der hinzuzufügende Artikel
*/
public void addItem(CartItem item) {
this.items.add(item);
}
/**
* Liefert den Gesamtpreis aller Artikel im Einkaufswagen
* @return
*/
public double getTotalCost() {
double cost = 0;
for (CartItem item : items) {
cost += item.getCost();
}
return cost;
}
/**
* Gibt den Kassenbon für den Einkaufswagen aus
*/
public String toString() {
StringBuilder sb = new StringBuilder();
for (CartItem item : items) {
sb.append(item);
}
sb.append("%nSumme:%55.2f%n".formatted(this.getTotalCost()));
return sb.toString();
}
}

View File

@ -0,0 +1,11 @@
package com.mymart;
public class Test {
public static void main(String[] args) {
ShoppingCart sc = new ShoppingCart();
sc.addItem(new CartItem("Erdbeeren", 15, 0.5));
sc.addItem(new CartItem("Vollkornbrot", 2, 2.7));
System.out.println(sc);
}
}