Я новичок в Java.Я должен сделать корзину.Но я застрял на ссылке.
Пожалуйста, помогите мне!
Я пытался сделать закрытую переменную-член ShoppingCart в классе Customer.Но я думаю, что это не правильный путь.
Customer.java
public class Customer {
private String id;
private String firstName;
private String lastName;
private ShoppingCart s;
public Customer(String id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
s = new ShoppingCart();
}
@Override
public String toString() {
return ("Customer ID is: " + this.id + "\n" + "Customer's name is: "
+ this.firstName + " " + this.lastName + "\n\n"
+ s.toString());
}
}
Test.java
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Customer c1 = new Customer("12345", "David", "Smith");
//This sentence doesn't work because of s.
c1.s.addBooktoCart("Harry Potter", "Fantasy Genre", 10.99, 309);
}
}
ShoppingCart.java
public class ShoppingCart {
private int itemCount;
private double totalPrice;
private static int capacity;
private Item[] cart;
public ShoppingCart()
{
capacity = 5;
itemCount = 0;
totalPrice = 0.0;
cart = new Item[capacity];
}
public void addBooktoCart(String title, String description, double price, int pageCount) {
if (itemCount < 5) {
Item item = new Book(title, description, price, pageCount);
totalPrice += price;
cart[itemCount] = item;
itemCount += 1;
}
else {
System.out.println("The maximum number that you can input is 5." +
"You cannot add item anymore");
}
}
}
Я хочувызвать addBooktoCart, который находится в классе ShoppingCart в Test.java.Но это не работает.Что мне делать, если я позвоню addBooktoCart?И если есть другая проблема.Пожалуйста, дайте мне знать!