Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Build the ShoppingCart class with the following specifications. Note: Some can be method stubs (empty methods) initially, to be completed in later steps.
Private fields
String customerName - Initialized in ddefault constructor to "none"
String currentDate - Initialized in ddefault constructor to "January 1, 2016"
ArrayList cartItems
Default constructor
Parameterized constructor which takes the customer name and date as parameters (1 pt)
Public member methods
getCustomerName () accessor (1 pt)
getDate () accessor (1 pt)
addItem ()
Adds an item to cartItems array. Has parameter ItemToPurchase. Does not return anything.
...
ok so i got lost around the arrayList cartItems. I am not sure if I should declare it as a String or an int. Also not sure if how I declared it was correct or the way the asked it to be done. I also created a class called ItemToPurchase that goes with this and I need to create a class called ShoppingCartManager that has the main method. Here's what I have so far (I took some things out of the ShoppingCart class.)
ItemToPurchase.java
public class ItemToPurchase {
private String itemName;
private String itemDescription;
private int itemPrice;
private int itemQuantity;
public ItemToPurchase() {
itemName = "none";
itemPrice = 0;
itemQuantity = 0;
itemDescription = "none";
}
public void setDescription(String description) {
itemDescription = description;
}
public String getDescription() {
return itemDescription;
}
public String printItemCost() {
String str = getName() + " " + getQuantity() + " " + getPrice() + " " + (getQuantity() * getPrice());
return str;
}
public String printItemDescription() {
String k = getName() + " " + getDescription();
return k;
}
public void setName(String name) {
itemName = name;
}
public String getName() {
return itemName;
}
public void setPrice(int price) {
itemPrice = price;
}
public int getPrice() {
return itemPrice;
}
public void setQuantity(int quantity) {
itemQuantity = quantity;
}
public int getQuantity() {
return itemQuantity;
}
}
ShoppingCart.java
import java.util.ArrayList;
public class ShoppingCart {
Scanner sc = new Scanner(System.in);
private String customerName;
private String currentDate;
private ArrayList<String> cartItems = new ArrayList<String>();
public ShoppingCart(String customerName, String currentDate) {
customerName = "none";
currentDate = "January 1, 2016";
}
public void getCustomerName() {
}
public void getDate() {
}
public void addItem(String itemName) {
cartItems.add(itemName);
}
}
It seems to me your ArrayList does not need to hold ints or Strings, but rather ItemToPurchase instances. This would mean changing your ArrayList declaration to private ArrayList<ItemToPurchase> cartItems = new ArrayList<ItemToPurchase>(); This way you can add ItemToPurchase objects to the ArrayList, which I believe is what you are trying to do. Then change your addItem method in the ShoppingCart class to accept ItemToPurchase objects, instead of String objects.
public void addItem(ItemToPurchase item) {
cartItems.add(item);
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
In my program I have an abstract class TelephoneEntry which holds a TelephoneNumber(it implements Comparable) and an addres, then I have child classes Person and Company that extend the TelephoneEntry class.
abstract class TelephoneEntry {
protected TelephoneNumber number;
protected String address;
public abstract void description();
public TelephoneNumber getNumber() {
return number;
}
public void setNumber(TelephoneNumber number) {
this.number = number;
}
}
class Person extends TelephoneEntry {
protected String name;
protected String surname;
public Person(String name, String surname, String address, int code, long number) {
this.name = name;
this.surname = surname;
this.address = address;
this.number = new TelephoneNumber(code, number);
}
#Override
public void description() {
System.out.println("Name: " + name);
System.out.println("Surname: " + surname);
System.out.println("Address: " + address);
System.out.println("TelephoneNumber: " + number.toString());
}
}
class Company extends TelephoneEntry {
protected String name;
public Company(String name, String address, int code, long number) {
this.name = name;
this.address = address;
this.number = new TelephoneNumber(code, number);
}
#Override
public void description() {
System.out.println("Name: " + name);
System.out.println("Address: " + address);
System.out.println("TelephoneNumber: " + number.toString());
}
}
public class TelephoneNumber implements Comparable<TelephoneNumber> {
private int countryCode;
private long localNumber;
public TelephoneNumber(int code, long number) {
countryCode = code;
localNumber = number;
}
#Override
public int compareTo(TelephoneNumber otherNumber) {
if (Integer.compare(getCountryCode(), otherNumber.getCountryCode()) != 0) {
return Long.compare(getLocalNumber(), otherNumber.getLocalNumber());
} else
return Integer.compare(getCountryCode(), otherNumber.getCountryCode());
}
public String toString() {
String out = "";
out += ("+" + countryCode + " " + localNumber);
return out;
}
}
But when I try passing them to a tree map defined as
TreeMap<TelephoneNumber, TelephoneEntry> map = new TreeMap<>();
I get an error stating that:
"The method add(TelephoneNumber, Person) is undefined for the type TreeMap<TelephoneNumber,TelephoneEntry>"
"The method add(TelephoneNumber, Company) is undefined for the type TreeMap<TelephoneNumber,TelephoneEntry>"
I'm not sure what may the cause of this error be as they both inherit the used key from TelephoneEntity.
Maps have put() method, not an add() method, for adding entries.
Change your code to:
myMap.put(myTelephoneNumber, myTelephoneEntry);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
My assignment asks us to make the following variables private as shown: private String title;
private double price; --------these variables can be found on the file Book.java.
My code isn't able to retrieve these variables because they are not visible for the file Textbook.java. How can I keep these variables private, but still get the output desired when I run the TextbookApp.java file. Here is the desired output:
Here is the output I'm getting right now:
Book.java
package assignment2;
public class Book {
private String title;
private double price;
public Book ()
{
title = "";
price = 0.0;
}
public Book (String t, double p)
{
title = t;
price = p;
}
public void setTitle(String t)
{
title = t;
}
public String getTitle()
{
return title;
}
public void setPrice(double p)
{
price = p;
}
public double getPrice()
{
return price;
}
public String toString()
{
return title + " " + price;
}
}
BookApp.java
package assignment2;
public class BookApp {
public static void main(String[] args) {
Book b1 = new Book();
b1.setTitle("John Doe");
b1.setPrice(8.5);
System.out.println(b1.toString());
Book b2 = new Book("Ann Smith", 9.7);
System.out.println(b2.toString());
}
}
Textbook.java
package assignment2;
public class Textbook extends Book{
private int courseID;
public Textbook()
{
title = "";
price = 0.0;
courseID = 0;
}
public Textbook (String t, double p, int ID)
{
title = t;
price = p;
courseID = ID;
}
public void setCourseID(int ID)
{
courseID = ID;
}
public int getCourseID()
{
return courseID;
}
public String toString()
{
return title + " " + price + " " + courseID;
}
}
TextbookApp.java
package assignment2;
public class TextBookApp extends Textbook {
public static void main(String[] args) {
Book b = new Book ("Ann Smith", 9.7);
System.out.println(b.toString());
Textbook tb1 = new Textbook();
tb1.setTitle("John Doe");
tb1.setPrice(8.5);
tb1.setCourseID(2050);
System.out.println(tb1.toString());
Textbook tb2 = new Textbook("Ann Smith", 9.7, 3090);
System.out.println(tb2.toString());
}
}
You can solve the error by calling the appropriate superclass constructor or method in Book from your Textbook subclass:
package assignment2;
public class Textbook extends Book{
private int courseID;
public Textbook()
{
courseID = 0;
}
public Textbook (String t, double p, int ID)
{
super(t, p);
courseID = ID;
}
public void setCourseID(int ID)
{
courseID = ID;
}
public int getCourseID()
{
return courseID;
}
public String toString()
{
return super.toString() + " " + courseID;
}
}
The no-argument constructure Textbook() will automatically call the no-argument constructor Book(), so you don't need to set title and price explicitly in Textbook().
I am trying to ignore the existing item that I added in the duplicate.
Normally, if the item does not exist it will eventually added the item to the
LinkedList
When I try to added item again, I just wanted to ignore the adding process and the increment the value by 1.
But the problem is it keep adding the items to the LinkedList.
Can someone explain to me?
class Item{
Store store;
String name;
String code;
String number;
public Item(String name, String code){
this.name = name;
this.code = code;
number = 0;
}
public boolean itemExists(String name, String code){
return this.name.equals(name) && this.code.equals(code);
}
public void increment(){ number++; }
#Override
public String toString(){ return store.getName()+ " " + name + " " + code + " " +number; }
}
Items will be added to the factory.
class Factory{
private LinkedList<Item> items = new LinkedList<Item>():
private String name;
private String number;
public Factory(String name, String number){
this.name = name;
this.number = number;
}
public void getName(){
return name;
}
public void addItem(String name, String code){
items.add(new Item(this, name, code));
}
#Override
public String toString(){ return name + " " + number; }
public List<Item> getItems{
return items;
}
}
The factory then delivery to the store.
class Store{
private LinkedList<Factory> factories = new LinkedList<>();
public Store(){
factories.add(new Factory("MayFlower", "01");
factories.add(new Factory("SunFlower", "02");
factories.get(0).addItem("GTA", "001A");
factories.get(0).addItem("GTA", "002A");
factories.get(0).addItem("GTA", "003A");
factories.get(1).addItem("Sonic", "022A");
factories.get(1).addItem("Sonic", "023B");
factories.get(1).addItem("Sonic", "024C");
}
public List<Item> getItemFromFact(){
List<Item> temp = new ArrayList<>();
for(Factory factory: factories)
for(Item item: factory.getItems())
temp.add(item);
return temp;
}
}
The customer buy items at the store.
class Customer{
private LinkedList<Item> items = new LinkedList<>();
public static void main(String args[]){
new Customer.view();
}
private void view(){
for(Item item: items)
System.out.println(item);
}
private void adding(){
String name = "GTA";
String code = "001A":
List<Item> item = item(name, code);
if(!item.isEmpty()){
items.add(item);
item.increment(); // will increment the value;
}
else{
System.out.println("Item does not exists");
}
}
private List<Item> item(String name, String code){
List<item> temp = new ArrayList<>();
List<item> fromStore = new Store().getItemFromFact();
for(Item item: fromStore)
if(item.itemExists(name, code))
temp.add(item)
return temp;
}
}
The main problem is in the item class under item(). If I try with the same item again, it will just add another it become like this.
MayFlower GTA 001A 1
MayFlower GTA 001A 1
The result should be
MayFlower GTA 001A 2
after I added another item.
I problem I have is that I don't know how to match the item from exisiting.
If someone know the solution.
That's would be very helpful thanks.
There are so many problems in your design and code. I've discussed some of them as given below:
I do not understand why you need a reference to Store in Item. An Item should not know which Store or Factory it is going to belong to.
I also didn't understand the purpose of the attribute, number in Store. An Item shouldn't know how many numbers of it is present in a Store or Factory. If you keep it for any reason, it should be of a numeric type (e.g. int, double etc.) so that you can perform arithmetic operations on it.
Instead of a LinkedList of Item objects in Factory, you should have a variable of type, Map<String, Integer> and you can call it stock. The key in this Map is the unique identifier of the item, which is the combination code and name as per your requirement and the value will be the available number/quantity of the Item. Given below is a minimal verifiable example of how you can maintain stock:
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
class Item {
String name;
String code;
public Item(String name, String code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public String getCode() {
return code;
}
#Override
public String toString() {
return "Name: " + name + "Code :" + code;
}
}
class Factory {
private Map<String, Integer> stock = new HashMap<String, Integer>();
private String name;
public Factory(String name) {
this.name = name;
}
public void addItem(Item item) {
if (item != null) {
String key = item.getName() + ":" + item.getCode();
stock.put(key, stock.getOrDefault(key, 0) + 1);
}
}
public void showStock() {
for (Entry<String, Integer> entry : stock.entrySet()) {
System.out.println("Item = " + entry.getKey() + ", Available quantity = " + entry.getValue());
}
}
}
public class Main {
public static void main(String[] args) {
Factory factory = new Factory("MayFlower");
factory.addItem(new Item("GTA", "001A"));
factory.addItem(new Item("GTA", "001A"));
factory.addItem(new Item("GTA", "002A"));
factory.addItem(new Item("GTA", "003A"));
factory.addItem(new Item("GTA", "003A"));
factory.addItem(new Item("GTA", "003A"));
factory.showStock();
}
}
Output:
Item = GTA:002A, Available quantity = 1
Item = GTA:003A, Available quantity = 3
Item = GTA:001A, Available quantity = 2
So I'm practictising Object oriented programming and I'm trying to make a Book class that can have multiple authors but I don't know how to do it.
This is the UML of the excerise:
This is my author class which works fine:
public class Author {
//attributen van de class auteur
private String name;
private String email;
private char gender;
//constructor
public Author (String name, String email, char gender){
this.name = name;
this.email = email;
this.gender= gender;
}
//methodes
public String getName(){
return name;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public char getGender(){
return gender;
}
//methode om gegevens van autheur opbject op te halen
public String toString(){
return "Author[name = " + name + ", email = " + email + ", gender = " + gender + "]";
}
}
And here is the Book class that I tried to make:
public class Book {
//attributes
private String name;
private Author authors [] = new Author[2];
private double price;
private int qty = 0;
public Book(String name, Author authors[], double price, int qty) {
this.name = name;
authors[0] = new Author("Tan Ah Teck", "AhTeck#somewhere.com", 'm');
authors[1] = new Author("Paul Tan", "Paul#nowhere.com", 'm');
this.price = price;
this.qty = qty;
}
public String getName() {
return name;
}
public Author getAuthors() {
return authors[authors.length];
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public String toString() {
return "Book [name = " + name + " authors = " + authors[0] + " email = " + authors[0].getEmail() + " price = " + price + " qty = " + qty + "]";
}
//methodes om gegevens van de autheur op te halen
public String getAuthorNames() {
return authors[].getName();
}
public String getAuthorEmails() {
return authors[].getEmail();
}
public char getAuthorGenders() {
return authors[].getGender();
}
}
So when I try to make an object of a book in my main.java the constructor of the book class is not working.
Also at this function : public Author getAuthors() {
it says: Array index is out of bounds.
Also at the methods to get the author names, emails and genders it says: Unknown class authors[].
How can I modify this book class so a book can have one or more authors? (the Book class did work when a book only could have 1 author, but now I'm trying to change it so a book can have more authors)
Any kind of help is appreciated!
When you don't provide this keyword for authors within your constructor, the code works with your constructor parameter not with your class variable, therefore you encounter that problem.
try removing the authors from constructor like this:
public Book(String name, double price, int qty)
it says: Array index is out of bounds
First, it cannot say that with the given code, because it doesn't compile with the last three methods.
And well, authors.length == 2, and your array only has indicies 0 and 1
If you want to actually "get the authors", you want to return the array, not a specific one
public Author[] getAuthors() {
return authors;
}
And if you did want to get one, then add the index.
It's also good habit to add boundary checking
public Author getAuthor(int index) {
return (index < 0 || index >= authors.length) ? null : authors[index];
}
However, with these fixes, you might see null now because you actually have two list; the one you will pass to new Book(), and the field within the instance of that object.
Rather, you will want to do
private Authors[] authors;
public Book(String name, Author authors[], double price, int qty) {
this.name = name;
this.authors = authors;
And in the main method create the authors
Author[] authors = new Author[] {
new Author("Tan Ah Teck", "AhTeck#somewhere.com", 'm'),
new Author("Paul Tan", "Paul#nowhere.com", 'm')
};
Book b = new Book("name", authors, ...);
System.out.println(Arrays.toString(b.getAuthors()));
Also at the methods to get the author names, emails and genders it says: Unknown class authors[]
Because authors[].blah is not valid syntax. You need to loop over each of the array values to get the respective fields.
I would suggest Arrays.stream methods and StringJoiner for handling this
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am having this error where it prints out just the last element entered, prints out it the same amount of times as there are elements that are supposed to be in the array.
I have tested it with a System.out.println and the elements that are being added appear to be correct. How do I fix this error?
package stock.control.system;
import java.util.*;
public class StockArrayList implements StockList {
private ArrayList<StockItem> StockItems;
private int index = 0;
private int update;
private int counter = 0;
public StockArrayList() {
StockItems = new ArrayList<StockItem>(counter);
}
#Override
public void addItem(StockItem item) {
StockItem aItem = new StockItem(StockItem.getItemID(),
StockItem.getItemDesc(),
StockItem.getPrice(),
StockItem.getQuantity(),
StockItem.getReOrderLevel());
StockItems.add(counter, aItem);
counter++;
}
#Override
public String formatStockList(){
String temp = StockItem.format();
for (StockItem items : StockItems) {
temp = temp + items.arrayFormat() + "\n";
}
return temp;
}
}
The main method:
public class StockArrayListTester {
public static void main(String[] args) {
StockArrayList Stock = new StockArrayList();
Stock.addItem(new StockItem("P123","1TB Hard drive",75.00,267,50));
Stock.addItem(new StockItem("P125","i7 6800HQ Processor",257.00,113,45));
Stock.addItem(new StockItem("P129","i5 500HQ Processor",127.00,10,45));
Stock.deleteItem("P129");
System.out.printf(Stock.formatStockList());
}
}
the stock item class
package stock.control.system;
import java.util.*;
public class StockItem {
private static String itemID; // Five alpha-numeric characters
private static String itemDesc; // Item description
private static double price; // Item price in pounds sterling
private static int quantity; // Quantity in stock
private static int reOrderLevel; // Level at which to re-order
public StockItem(String itemID, String itemDesc, double price, int quantity, int reOrderLevel) {
this.itemID = itemID;
this.itemDesc = itemDesc;
this.price = price;
this.quantity = quantity;
this.reOrderLevel = reOrderLevel;
}
#Override
public String toString() {
String toString ="[Item ID = " + this.itemID + ", Item Description = " +
this.itemDesc + ", Price = " + this.price + ", Quantity = " +
this.quantity + ", Re Order Level = " + this.reOrderLevel + "]";
return toString;
}
public static String format() {
String format = " STOCK ITEMS"
+ String.format("\n%-10s%-30s%-10s%-12s%-14s%-10s%-30s%-10s%-12s%-14s\n",
"ItemID","Item Description",
"Price","Quantity", "Re Order Level", "\n******",
" ****************"," *****", " ********",
" **************");
return format;
}
public String arrayFormat() {
return String.format("%-10s%-30s%-10s%-12s%-14s",
StockItem.getItemID(),
StockItem.getItemDesc(),
StockItem.getPrice(),
StockItem.getQuantity(),
StockItem.getReOrderLevel());
}
public static String getItemID(){
return itemID;
}
public static String getItemDesc() {
return itemDesc;
}
public static double getPrice() {
return price;
}
public double setPrice(double price) {
this.price = price;
return price;
}
public static int getQuantity() {
return quantity;
}
public int setQuantity(int quantity) {
this.quantity = quantity;
return quantity;
}
public static int getReOrderLevel(){
return reOrderLevel;
}
public int setReOrderLevel(int reOrderLevel){
this.reOrderLevel = reOrderLevel;
return reOrderLevel;
}
}
The output I get is:
STOCK ITEMS
ItemID Item Description Price Quantity Re Order
P129 i5 500HQ Processor 127.0 10 45
P129 i5 500HQ Processor 127.0 10 45
P129 i5 500HQ Processor 127.0 10 45
BUILD SUCCESSFUL (total time: 0 seconds)
As a rule, never set static fields in a constructor. It is almost certainly a bug. IMHO, this should be a compiler error but it's not.
In this case, you are expecting each instance of StockItem to be different, however by making the fields static you are ensuring there is only one copy, only one value for those fields. I suggest you make them instance fields.
public class StockItem {
private final String itemID; // Five alpha-numeric characters
private final String itemDesc; // Item description
private double price; // Item price in pounds sterling
private int quantity; // Quantity in stock
private int reOrderLevel; // Level at which to re-order
public StockItem(String itemID, String itemDesc, double price, int quantity, int reOrderLevel) {
this.itemID = itemID;
this.itemDesc = itemDesc;
this.price = price;
this.quantity = quantity;
this.reOrderLevel = reOrderLevel;
}
It's been a little while since I've used Java but it seems weird that in your addItem() method in your StockList class that you pass in a parameter 'item' but then never use it inside the method.
Why are you trying to "get" all of the properties of the stock item to add when you are passing them in to the function as a StockItem object?
Guess something is wrong here:
#Override
public void addItem(StockItem item) {
StockItem aItem = new StockItem(StockItem.getItemID(),
StockItem.getItemDesc(), StockItem.getPrice(), StockItem.getQuantity(), StockItem.getReOrderLevel());
StockItems.add(counter, aItem);
counter++;
}
All those getters are static methods. It does not make sense to me since I would think you want to get instance variables belonging to different objects. You must have initialiazed the StockItem class instance variables with the values printed out, otherwise I do not think your code would even compile.
Anyway why not adding the item passed as a parameter directly to the stock list?
Like so:
#Override
public void addItem(StockItem item) {
StockItems.add(counter, item);
counter++;
}