I have a basket where products are added to and for each product there is a delete button:
Whenever I click the bottom button it deletes the bottom product, the problem is it also deletes the last item when clicked in the top button until the amount is 0 and the item is gone it deletes the 2nd one on the bottom (in this case the first item)
Here is my basket class code:
package model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Observable;
import main.WinkelApplication;
import view.Payment;
public class Basket extends Observable {
private final Map<Product, Integer> products;
public Basket() {
super();
products = new LinkedHashMap<Product, Integer>(); //Map zorgt ervoor dat keys??? aan values word gebonden (dit is een soort van variabele[i], i staat voor de key
}
public void addProduct(Product product) {
// check if product is allready added to the basket
if (products.containsKey(product)) {
products.put(product, products.get(product) + 1);
} else {
products.put(product, 1);
}
setChanged();
notifyObservers();
}
public void deleteProduct(Product product) {
// check if product is allready added to the basket
int i = WinkelApplication.getBasket().getProductAmount(product);
int id = product.getProductId();
if (WinkelApplication.getBasket().getProductAmount(product) == 1) {
products.remove(product);
WinkelApplication.getInstance().showPanel(new view.Payment());
}else{
i--;
products.put(product, i);
WinkelApplication.getInstance().showPanel(new view.Payment());
}
if (products.size() == 0) {
WinkelApplication.getInstance().showPanel(new view.CategoryList());
}
}
public void empty() {
products.clear();
setChanged();
notifyObservers();
}
public List<Product> getProducts() {
List<Product> list = new LinkedList<Product>(products.keySet());
return list;
}
public int getProductAmount(Product product) {
return products.get(product);
}
public int size() {
return products.size();
}
public double getTotalCosts() {
double total = 0.0;
for (Entry<Product, Integer> entry : products.entrySet()) { //gaat de lijst van producten af in basket, en doet de prijs bij totaal * het hoeveelheid van zo'n product
total += entry.getKey().getPrice() * entry.getValue();
}
return total;
}
}
As seen in the deleteProduct method I did products.remove(product) so I assume it then takes the last Item, if I System out the hash map it shows me: {Cars=2, Dames onderbroek=1} (according to the picture above). How can I make sure it deletes the selected one instead of the last one in the list?
The product class:
package model;
public class Product {
private int productId;
private int categorieId;
private String name;
private String description;
private double price;
public Product() {
this(-1, -1, "", "", 0.0);
}
public Product(int product_id, int categorie_id, String name, String description, double price) {
this.productId = product_id;
this.categorieId = categorie_id;
this.name = name;
this.description = description;
this.price = price;
}
/**
* #return the productId
*/
public int getProductId() {
return productId;
}
/**
* #param productId the productId to set
*/
public void setProductId(int productId) {
this.productId = productId;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the description
*/
public String getDescription() {
return description;
}
/**
* #param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* #return the price
*/
public double getPrice() {
return price;
}
/**
* #param price the price to set
*/
public void setPrice(double price) {
this.price = price;
}
/**
* #return the categorieId
*/
public int getCategorieId() {
return categorieId;
}
/**
* #param categorieId the categorieId to set
*/
public void setCategorieId(int categorieId) {
this.categorieId = categorieId;
}
#Override
public String toString() {
return name;
}
#Override
public boolean equals(Object obj) {
boolean value;
if (obj instanceof Product) {
value = this.productId == ((Product)obj).productId; //VB: product1 (met ID 1) past deze methode toe, en geeft product2 als parameter: deze method geeft dan false terug.
} else {
value = super.equals(obj); //van wat is Product een subclass van? en wat heeft dit voor nut?
}
return value;
}
#Override
public int hashCode() { //wth is dit?
return 13 * 3 + this.productId;
}
}
Unfortunately you have not sent us the class Product but I can assume that you have not implemented hashCode() and equals() for this class.
The short answer - do this and your logic will work.
The longer answer is that hash mechanism uses these methods to identify your object. By default hashCode() returns the "address" in java heap, so 2 different instances of Product are different even if all their fields are equal. Pay attention that if equals() returns true hashCode() must return equal value for both objects.
WinkelApplication.getBasket() maybe delivers another basket?
Not an answer but one could get an error when the product is not in products.
public int getProductAmount(Product product) {
Integer i = products.get(product);
return i == null ? 0 : i.intValue();
}
Related
Doing my homework, and trying to get some values to spit out onto a table in IntelliJ right now. I'm following a webinar series, and can't figure out what I'm doing wrong. I try to add a part to the system, but I get an error that "non-static method addPart(classes.Part) cannot be referenced from a static context." Along with three other errors around the same area in my MainApplication.java file.
package project.wfc482project;
import classes.InHouse;
import classes.Outsourced;
import classes.Part;
import classes.Inventory;
import classes.Product;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class MainApplication extends Application {
#Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("MainMenu.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 320, 240);
stage.setTitle("C482 Inventory Management System");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
// Sample values, Parts, and Products
InHouse inhouse1 = new InHouse(1, "Tire", 10.99, 10, 0, 20, 125);
InHouse inhouse2 = new InHouse(2, "Strut", 12.99, 27, 0, 30, 124);
Outsourced outsourced1 = new Outsourced(3, "Tubing", 7.50, 5, 0, 15, "Super Parts");
Outsourced outsourced2 = new Outsourced(5, "Lens", 3.50, 22, 0, 25, "Auto Glass");
Inventory.addPart(inhouse1);
Inventory.addPart(inhouse2);
Inventory.addPart(outsourced1);
Inventory.addPart(outsourced2);
launch();
// Call static members
}
}
And here's the Inventory.java page that I am trying to pull from, which pulls from a Parts.java page that I'll throw up here in a sec...
package classes;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class Inventory {
private static int partId = 0;
private static int productId = 0;
private static ObservableList<Part> allParts = FXCollections.observableArrayList();
private static ObservableList<Product> allProducts = FXCollections.observableArrayList();
public static ObservableList<Part> getAllParts() {
return allParts;
}
public ObservableList<Product> getAllProducts() {
return allProducts;
}
public void addPart(Part newPart) {
allParts.add(newPart);
}
public void addProduct(Product newProduct) {
allProducts.add(newProduct);
}
public static int getNewPartId() {
return ++partId;
}
public static int getNewProductId() {
return ++productId;
}
public Part lookupPart(int partId) {
Part partFound = null;
for (Part part : allParts) {
if (part.getId() == partId) {
partFound = part;
}
}
return partFound;
}
public ObservableList<Part> lookupPart(String partName) {
ObservableList<Part> partsFound = FXCollections.observableArrayList();
for (Part part : allParts) {
if (part.getName().equals(partName)) {
partsFound.add(part);
}
}
return partsFound;
}
public Product lookupProduct(int productId) {
Product productFound = null;
for (Product product : allProducts) {
if (product.getId() == productId) {
productFound = product;
}
}
return productFound;
}
public ObservableList<Product> lookupProduct(String productName) {
ObservableList<Product> productsFound = FXCollections.observableArrayList();
for (Product product : allProducts) {
if (product.getName().equals(productName)) {
productsFound.add(product);
}
}
return productsFound;
}
public void updatePart(int index, Part selectedPart) {
allParts.set(index, selectedPart);
}
public void updateProduct(int index, Product selectedProduct) {
allProducts.set(index, selectedProduct);
}
public boolean deletePart(Part selectedPart) {
if (allParts.contains(selectedPart)) {
allParts.remove(selectedPart);
return true;
}
else {
return false;
}
}
public boolean deleteProduct(Product selectedProduct) {
if (allProducts.contains(selectedProduct)) {
allProducts.remove(selectedProduct);
return true;
}
else {
return false;
}
}
}
The Part Class:
package classes;
public abstract class Part {
// Declare fields
private int id;
private String name;
private double price;
private int stock;
private int min;
private int max;
// Declare Constructor
public Part(int id, String name, double price, int stock, int min, int max) {
this.id = id;
this.name = name;
this.price = price;
this.stock = stock;
this.min = min;
this.max = max;
}
public Part() {
}
// Setters and Getters
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the price
*/
public double getPrice() {
return price;
}
/**
* #param price the price to set
*/
public void setPrice(double price) {
this.price = price;
}
/**
* #return the stock
*/
public int getStock() {
return stock;
}
/**
* #param stock the stock to set
*/
public void setStock(int stock) {
this.stock = stock;
}
/**
* #return the min
*/
public int getMin() {
return min;
}
/**
* #param min the min to set
*/
public void setMin(int min) {
this.min = min;
}
/**
* #return the max
*/
public int getMax() {
return max;
}
/**
* #param max the max to set
*/
public void setMax(int max) {
this.max = max;
}
}
And the InHouse class:
package classes;
public class InHouse extends Part{
private int machineId;
public InHouse(int id, String name, double price, int stock, int min, int max, int machineId) {
super(id, name, price, stock, min, max);
this.machineId = machineId;
}
public int getMachineId() {
return machineId;
}
public void setMachineId(int machineId) {
this.machineId = machineId;
}
}
I've tried looking up answers to this on here and Reddit, but I'm having a hard time making sense of it all.
I understand that I can't make a part for an abstract class, although that's what the webinar tells me to do (it's more likely that that's what I'm interpreting that as, but I'm turned around and not understanding it).
Change the method Inventory.addPart() to a static method. Change this:
public void addPart(Part newPart) {
allParts.add(newPart);
}
to this
public static void addPart(Part newPart) {
allParts.add(newPart);
}
So I'm trying to add a book to an array list. I'm having a little trouble due to the fact the book must include 3 parameters (string author, string title, string id) The reason I'm having trouble is due to 2 methods that have to be used on it. One method is for finding matching titles the other wants me to list all books currently in the array. Right now my code looks like this:
import java.util.ArrayList;
import java.util.Iterator;
/**
* A class contaning books.
*
* #author ()
* #version (21/11/2021)
*/
public class Library
{
private ArrayList<String> books;
private String name;
/**
* Makes an arraylist and sets the librarys name
*/
public Library(String aName)
{
books = new ArrayList<>();
name = aName;
}
/**
* Adds a book to the arraylist books
*/
public void addBook(String author, String title, String id)
{
books.add(author);
books.add(title);
books.add(id);
}
/**
* calculates fine of a late book
*/public double calculateFine (double bookPrice, int dayLate)
{
return (double) (bookPrice/50)*dayLate;
}
/**
* creates a private list to store matched books
*/
public ArrayList<String> booksClone = new ArrayList<>();
/**
*
*/
public ArrayList getMatchingBooks(String bookMatch)
{
for (int i =0; i < books.size(); i++)
{
if(books.get(i).equals(bookMatch));
booksClone.add(bookMatch);
}
return booksClone;
}
/**
*
*/
public boolean isAvailable(String book, boolean onLoan)
{
for (int i=0; i <books.size();i++)
{
if(books.get(i)==book)
if (onLoan ==true);
}
return false;
}
/**
* Prints out all books currently listed.
*/
public void listAllBooks()
{for (int i=0; i < books.size();i++)
System.out.println(books.get(i));
}
/**
*
*/
public void loanBook(String bookLoan, boolean onLoan)
{
for (int i=0; i < books.size();i++)
{
if (books.get(i)==bookLoan)
onLoan = true;
}
}
/**
*
*/
public void removeBook(String book)
{
for (int i=0; i < books.size();i++)
{
if (books.get(i).equals(book))
books.remove(book);
else
System.out.println("Book not found");
}
}
}
as you can see my current code takes the title author and id and links them to separate index's so when i try to search for a title i can not find the author.
I'm sorry if this is a obvious question I think I've just gotten myself lost any help and or advice is appreciated.
If you add the 3 String like this on the library arraylist, nothing will link them together.
To save the 3 String togeter on the list, you need to create an Object - lets name it "Book" - that will have 3 variables: author, title & id.
import java.util.ArrayList;
import java.util.Iterator;
/**
* A class contaning books.
*
* #author ()
* #version (21/11/2021)
*/
public class Library {
private ArrayList<Book> books;
private String name;
/**
* Makes an arraylist and sets the librarys name
*/
public Library(String aName) {
books = new ArrayList<>();
name = aName;
}
/**
* Adds a book to the arraylist books
*/
public void addBook(String author, String title, String id) {
books.add(new Book(author, title, id));
}
/**
* calculates fine of a late book
*/public double calculateFine (double bookPrice, int dayLate) {
return (double) (bookPrice/50)*dayLate;
}
/**
* creates a private list to store matched books
*/
public ArrayList<String> booksClone = new ArrayList<>();
/**
*
*/
public ArrayList getMatchingBooks(String bookMatch) {
for (int i =0; i < books.size(); i++)
{
if(books.get(i).equals(bookMatch));
booksClone.add(bookMatch);
}
return booksClone;
}
/**
*
*/
public boolean isAvailable(String bookTitle, boolean onLoan) {
for (int i=0; i <books.size();i++)
{
if(books.get(i).title==bookTitle)
if (onLoan ==true);
}
return false;
}
/**
* Prints out all books currently listed.
*/
public void listAllBooks() {for (int i=0; i < books.size();i++)
System.out.println(books.get(i));
}
/**
*
*/
// public void loanBook(String bookLoan, boolean onLoan) {
// for (int i=0; i < books.size();i++) {
// if (books.get(i)==bookLoan)
// onLoan = true;
// }
// }
/**
*
*/
public void removeBook(String bookId) {
for (int i=0; i < books.size();i++) {
if (books.get(i).id.equals(bookId))
books.remove(i);
else
System.out.println("Book not found");
}
}
class Book {
private String author;
private String title;
private String id;
public Book (String author, String title, String id) {
this.author=author;
this.title=title;
this.id=id;
}
public String toString(){
return id+": "+title+" from "+author;
}
}
public static void main(String[] args) {
Library lib = new Library("lib1");
lib.addBook("Mr X", "title1", "0");
lib.addBook("Mr X", "an other title", "8");
lib.addBook("Ms Y", "last title", "213b");
lib.listAllBooks();
}
}
Ps: Please add tab on your code.
I re-type these code from a book and somehow I got error " Cannot find symbol - class InventoryItem "
import java.util.Scanner;
public class ReturnObject {
public static void main(String[] args) {
InventoryItem item;
item = getData();
System.out.println("Des: " + item.getDescription() + " Unit: " +
item.Units());
}
public static InventoryItem getData() {
String desc;
int units;
Scanner keyboard = new Scanner(System.in);
System.out.print("enter descri: ");
desc = keyboard.nextLine();
System.out.print("number of unit: ");
units = keyboard.nextInt();
return new InventoryItem(desc, units);
}
}
I'm new to java please help
thank you.
I think this should be the InventoryItem you need.
/**
* This class uses three constructors.
*/
public class InventoryItem {
private String description; // Item description
private int units; // Units on-hand
/**
* No-arg constructor
*/
public InventoryItem() {
description = "";
units = 0;
}
/**
* The following constructor accepts a
* String argument that is assigned to the
* description field.
*/
public InventoryItem(String d) {
description = d;
units = 0;
}
/**
* The following constructor accepts a
* String argument that is assigned to the
* description field, and an int argument
* that is assigned to the units field.
*/
public InventoryItem(String d, int u) {
description = d;
units = u;
}
/**
* The setDescription method assigns its
* argument to the description field.
*/
public void setDescription(String d) {
description = d;
}
/**
* The setUnits method assigns its argument
* to the units field.
*/
public void setUnits(int u) {
units = u;
}
/**
* The getDescription method returns the
* value in the description field.
*/
public String getDescription() {
return description;
}
/**
* The getUnits method returns the value in
* the units field.
*/
public int getUnits() {
return units;
}
}
complete example click here and here
The class you are currently in cannot find the class (symbol) InventoryItem. You need to define this class & the getData method.
public class InventoryItem{
private String desc;
private int units;
public InventoryItem(){
Scanner keyboard = new Scanner(System.in);
System.out.print("enter descri: ");
desc = keyboard.nextLine();
System.out.print("number of unit: ");
units = keyboard.nextInt();
}
public static InventoryItem getData() {
return this;
}
}
maybe your InventoryItemclass:
public class InventoryItem {
private String desc;
private int units;
public InventoryItem(String desc, int units) {
this.desc=desc;
this.units=units;
}
public String getDescription() {
return desc;
}
public int Units() {
return units;
}
}
I have an assignment to make this Restaurant Program. it Consists of an Order Class a product class and the main class. Order has an ArrayList to hold the products. I create an instance of the Order and then I add items through my main method.A product has a name(string) a bar-code(string), and a price(float).
Then I have to output a receipt.But what if a customer orders more of one product? Do I instantiate everything one by one? Is a second Beer Product independent? Should I hold quantities somehow? If I want to add a second beer I have to create a new product Beer2 etc? I don't know beforehand how many products each order will hold and the quantity of each so Is this way of instantiating proper? Thanks
Note: it is still incomplete as I want to deal with this before I move on.
import java.util.Date;
public class MyRestaurantTester {
public static void main(String[] args) {
Date currentDate = new Date();
Paraggelia order1 = new Paraggelia(currentDate,"11B");
Product Beer = new Product("Amstel","111222",1.20f);
Product Beef = new Product("Pork Beef","333444",8.50f);
order1.add(Beer);
order1.add(Beef);
System.out.println(order1.getReceipt(30f));
}
}
Order Class(nevermind the name Paraggelia I gave it)
import java.util.ArrayList;
import java.util.Date;
/*Notes to self:
* -Work on Comments
* -Javadocs maybe?
* -try to optimize the rough code.
*/
/*Order class*/
public class Paraggelia {
private Date orderDate;
private String tableNumber;
private int customerCount;
private ArrayList<Product> listOfItems;
/*Constructor(s)*/
Paraggelia(Date orderDate,String tableNumber){
this.orderDate=orderDate;
this.tableNumber=tableNumber;
this.listOfItems = new ArrayList<Product>();
}
/*Add && Delete Products from the Order class*/
public void add(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}else{
listOfItems.add(p);
}
}
public void delete(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}
else
{
listOfItems.remove(p);
}
}
/** Calculates and returns the total price
* Usually called directly as a parameter of getReceipt function
* */
public static float getTotalPrice(){
return 0;
}
/** Creates and returns the final Receipt!
* -Display must consist of:
* Item$ - BarCode# - Item Amount#
* Total Price#
* Table Number#
*/
public String getReceipt(float totalPrice){
StringBuilder receipt = new StringBuilder();
for(int i =0; i<this.listOfItems.size();i++){
receipt.append(listOfItems.get(i).getName());
receipt.append("\n");
}
return new String(receipt);
}
/*Getters && Setters */
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getTableNumber() {
return tableNumber;
}
public void setTableNumber(String tableNumber) {
this.tableNumber = tableNumber;
}
public int getCustomerCount() {
return customerCount;
}
public void setCustomerCount(int customerCount) {
this.customerCount = customerCount;
}
}
Product Class:
public class Product {
private String Name;
private String barCode;
private float sellingPrice;
/*Constructors: */
Product(){}
Product(String Name,String barCode,float sellingPrice){
this.Name=Name;
this.barCode=barCode;
this.sellingPrice=sellingPrice;
}
/*Getters & Setters*/
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
public float getSellingPrice() {
return sellingPrice;
}
public void setSellingPrice(float sellingPrice) {
this.sellingPrice = sellingPrice;
}
}
Instead of ArrayList ( List ) you can use Map ( HashMap for example )
MyRestaurantTester
public class MyRestaurantTester {
public static void main(String[] args) {
Date currentDate = new Date();
Paraggelia order1 = new Paraggelia(currentDate,"11B");
Product Beer = new Product("Amstel","111222",1.20f);
Product Beef = new Product("Pork Beef","333444",8.50f);
order1.add(Beer, 1);
order1.add(Beef, 5);
System.out.println(order1.getReceipt(30f));
}
}
Paraggelia
class Paraggelia {
private Date orderDate;
private String tableNumber;
private int customerCount;
private Map<Product, Integer> listOfItems;
/*Constructor(s)*/
Paraggelia(Date orderDate,String tableNumber){
this.orderDate=orderDate;
this.tableNumber=tableNumber;
this.listOfItems = new HashMap<Product, Integer>();
}
/*Add && Delete Products from the Order class*/
public void add(Product p, int quantity){
if(p == null)
{
throw new IllegalArgumentException();
}else{
listOfItems.put(p, quantity);
}
}
public void delete(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}
else
{
listOfItems.remove(p);
}
}
/** Calculates and returns the total price
* Usually called directly as a parameter of getReceipt function
* */
public static float getTotalPrice(){
return 0;
}
/** Creates and returns the final Receipt!
* -Display must consist of:
* Item$ - BarCode# - Item Amount#
* Total Price#
* Table Number#
*/
public String getReceipt(float totalPrice){
StringBuilder receipt = new StringBuilder();
for(Map.Entry<Product,Integer> entry : this.listOfItems.entrySet()) {
Product product = entry.getKey();
Integer quantity = entry.getValue();
receipt.append(product.getName() + " " + quantity);
receipt.append("\n");
}
return new String(receipt);
}
/*Getters && Setters */
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getTableNumber() {
return tableNumber;
}
public void setTableNumber(String tableNumber) {
this.tableNumber = tableNumber;
}
public int getCustomerCount() {
return customerCount;
}
public void setCustomerCount(int customerCount) {
this.customerCount = customerCount;
}
}
OUTPUT:
Pork Beef 5
Amstel 1
Three basic approaches come to mind:
Instantiate each product individually
Instead of ArrayList, have another structure that can associate items with quantities; or,
Make a class Article, which belongs to a Product: Product beerProduct = new Product("beer", "0129", 1.37); Article beer = new Article(beerProduct), beer2 = new Article(beerProduct).
The first solution gives you a lot of flexibility (e.g. to discount individual articles for, say, being damaged). The second solution is more economical with objects. The third one captures the intuition that all the Heineken bottles are the same. It is really up to what you want to do - both approaches are equally valid, for some purpose.
I am doing an Object Oriented program which contains a class Catalog and a class Products. Catalog has a method which suppose to search a list of products with a specific name that are read from a file. Everything works but the getProducts is not working.
This is the Catalog class with the getProducts(String name)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*
public class Catalog{
private static int MAX_ITEMS = 10;
private Products[] list;
private int nextItem;
/**
* Default constructor
*/
public Catalog(){
list = new Products[MAX_ITEMS];
nextItem = 0;
}
/**
* Reads items from an input file.
*/
public void loadList(String fileName)
throws FileNotFoundException {
if ( (fileName != null) && (!fileName.equals("")) ) {
Scanner input = new Scanner(new File(fileName));
String newLine = null;
String name = null;
int quantity = 0;
double price = 0.0;
while (input.hasNextLine() && nextItem < MAX_ITEMS) {
if (input.hasNext()) {
name = input.next();
} else {
System.err.println("ERROR Not a String");
System.exit(2);
}
if (input.hasNextInt()) {
quantity = input.nextInt();
} else {
System.err.println("ERROR Not an integer");
System.exit(2);
}
if (input.hasNextDouble()) {
price = input.nextDouble();
} else {
System.err.println("ERROR Not a double");
System.exit(2);
}
list[nextItem] = new Products(name, quantity, price);
newLine = input.nextLine();
nextItem += 1;
}
}
return;
}
/**
* Calculate the total cost of products.
*/
public double getTotalPrice(){
double total = 0.0;
for(int i=0; i < nextItem; i++){
Products products = list[i];
total+=products.getTotalPrice();
}
return total;
}
/**
* Search Catalog items with a product name and returns it to caller
*/
public Products getProducts(String name){
**//search a list for string equality using the name of the product and returns it to the caller**
for(int i=0; i<nextItem; i++){
Products item = list[i];
if(item.equals(name)){
return item; //What is suppose to be returned or how to
//return it to the caller
}
public static void main(String[] args)
throws FileNotFoundException {
Catalog catalog= new Catalog();
catalog.loadList(args[0]);
System.out.println();
System.out.format("Total Price = %9.2f\n", catalog.getTotalPrice());
}
}
This is Products class
public class Products {
private String name;
private int quantity;
private double price;
/**
* Constructor.
*/
public Products(String name, int quantity, double price){
this.name = name;
this.quantity = quantity;
this.price = price;
}
/**
* Gets name of the product.
*/
public String getName(){
return this.name;
}
/**
* Gets the quantity of products.
*/
public int getQuantity(){
return this.quantity;
}
/**
* Gets the cost per product.
*/
public double getPrice(){
return price;
}
/**
* set quantity of the products.
*/
public void setQuantity(int quantity){
this.quantity=quantity;
}
/**
* Calculate the total price.
*/
public double getTotalPrice(){
return quantity * price;
}
/**
* Returns a spaced-separated list of the attributes.
*/
public String toString(){
toStr="";
toStr= toStr + getName();
return toStr;
}
This is the file
Football 2 15.50
Football-Jersey 2 30.95
ChapStick 1 3.87
Book 4 10.00
Book-Journal 1 5.00
You have:
public Products getProducts(String name){
...
for(int i=0; i<nextItem; i++){
...
Products item = list[i];
if(item.equals(name)) {
...
Notice that item is a Products but you are comparing it to the String, name. You would want to compare the product's name, e.g.:
if(item.getName().equals(name)) {
You can also use String.equalsIgnoreCase() if names are case-insensitive, possibly using trim() first if leading/trailing whitespace is an issue, too.
Item is an Object, so you can try to get the name by using dot like this
if(item.getName().equals(name))
or
if(item.getName.equalsIgnoreCase(name))