One of my classes will not output anything - java

so I need some advice, I have been working on some code for quite a while and I can never seem to find out why my code is screwing up terribly. It seems as if one of the toString lines in my Product class is not working properly. Here is the code:
import java.util.ArrayList;
public class lab24ArrayList
{
public static void main(String[]args)
{
ShoppingCart cart = new ShoppingCart();
Product hat = new Product ("Hat", 10);
Product scarf = new Product ("Scarf", 8);
Product legos = new Product ("Legos", 19);
Product dvd = new Product ("DVD", 12);
System.out.println("Removing DVD: "+cart.remove(dvd));
cart.add(hat);
cart.add(scarf);
cart.remove(scarf);
System.out.println("Removing Scarf: " +cart.remove(scarf));
cart.add(legos);
cart.add(dvd);
cart.add(legos);
System.out.println(cart);
}
}
class ShoppingCart
{
ArrayList <Product> cart;
public ShoppingCart()
{
cart = new ArrayList<Product>();
}
public int size()
{
int k = cart.size();
return k;
}
public void add(Product p)
{
cart.add(p);
}
public Product remove(Product p)
{
if(cart.contains(p))
{
cart.remove(p);
return p;
}
else
return null;
}
}
class Product
{
private String name;
private double price;
public Product(String _name, double _price)
{
name = _name;
price = _price;
}
public String getName() {return name;}
public double getPrice() {return price;}
public String toString() {return name + ": $"+price;}
}
When I put it in the compiler, all I get is this:
Removing DVD: null
Removing Scarf: null
ShoppingCart#c2f0bd7
When I need to get this:
Removing DVD: null
Removing Scarf: Scarf: $8
Items: 6
Total: $60.00
Hat: $10
Legos: $19
DVD: $12
Legos: $19

You're missing a toString() method on your ShoppingCart, that's why you get ShoppingCart#c2f0bd7. Override toString() in the ShoppingCartclass to build a string from the items within it.
You're also removing the Scarf twice, once here cart.remove(scarf) then also in System.out.println("Removing Scarf: " +cart.remove(scarf)).
To clarify how to print out the cart, you'll want to create a toString method in ShoppingCart similar to what you've done in Product:
public static String toString() {
StringBuilder stringBuilder = new StringBuilder();
for(Product product : cart) {
stringBuilder.append(product);
}
return stringBuilder.toString();
}
That creates a StringBuilder, loops through each product in the cart and appends it to the StringBuilder. You then return that string.

Related

How to get The Max Expensive Product in ArrayList?

My Question is:
I solved the class but still have stack in this method...
Add a findMostExpensiveProduct() method that searches a the most expensive product and return that project from the list of products of the buyer .
Notice: my Code for PurchasOrder class is:
So I need Help Please.
package midMalak;
import java.util.ArrayList;
public class PurchaseOrder {
private int OrderId;
private Buyer buyer;
private ArrayList<Product> products = new ArrayList<Product>();
public PurchaseOrder(int orderId, Buyer buyer) {
super();
OrderId = orderId;
this.buyer = buyer;
}
public int getOrderId() {
return OrderId;
}
public void setOrderId(int orderId) {
OrderId = orderId;
}
public Buyer getBuyer() {
return buyer;
}
public void setBuyer(Buyer buyer) {
this.buyer = buyer;
}
public ArrayList<Product> getProducts() {
return products;
}
public void setProducts(ArrayList<Product> products) {
this.products = products;
}
#Override
public String toString() {
return "PurchaseOrder [OrderId=" + OrderId + ", buyer=" + buyer + ", products=" + products + "]";
}
public void addProduct(Product P1) {
products.add(P1);
}
public double findMostExpensiveProduct(ArrayList<Product> products) {
}
public void removeProduct(Product ID) {
products.remove(ID);
}
public double calculateTotalPayment() {
double Toatl=0;
for(Product P1 : products) {
Toatl= P1.getPrice()+Toatl;
}
return Toatl;
}
}
public double findMostExpensiveProduct(ArrayList<Product> products) {
// Assuming product has the getPrice method
double mostExpensive = products.get(0).getPrice();
// Iterate through the list of products
for(int i = 1; i < products.size(); i++){
// if the next item is more expensive, assign that value as the most expensive
if (mostExpensive < products.get(i).getPrice()){
mostExpensive = products.get(i).getPrice();
}
}
return mostExpensive;
}
Normally I would do something like this to get this answer, although I am sure there are better ways of searching ArrayLists
public double findMostExpensiveProduct(ArrayList<Product> products) {
double mostExpensive = 0;
Product expensiveProduct;
for(Product P1 : products) {
if(P1.getPrice() > mostExpensive){
expensiveProduct = P1;
mostExpensive = P1.getPrice();
}
}
return expensiveProduct; // or expensiveProduct.getPrice() for actual price
}
This is how I would do this in other languages. I have also assumed there is a class method getPrice to return the price.
In general to get the max of any numeric value in a list or array do the following:
initialize max to the first element at index 0.
starting with the second index (1) iterate thru the list and compare the current element to `max'. If current is > than max, replace max with current.
If you want to save one or more values of the object or the object itself to be associated with max then you must also save those values when max is altered.
Note: Sometimes it is not convenient to initialize max to the first element. So initialize max to the smallest value possible for that numeric type (e.g. Integer.MIN_VALUE). Then iterate thru the entire list as above.
The same procedure can be used to find the minimum. Just reverse your comparison sign and initialize, if necessary, to Integer.MAX_VALUE.
Finally, this is the basic algorithm. There are enhancements to the Java API such as streams which can facilitate the process.

Multiple products in a single client(arrayList)

I've been asked to program a small online sales aplication.
It sounds very simple in theory (but it's been a hell for me). I'm just supposed to have an arrayList with about 5 products and then have a client buy 1 to 5 products and print the sales total.
public class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public String printInfo() {
return "Product: " + name + " Cost: " + price;
}
}
Then I have a client class:
public class Cliente {
private String name;
private int numPedido;
ArrayList<Producto> products = new ArrayList<Producto>();
public void listBuilder() {
Producto shirt = new Producto("Shirt", 30);
Producto tshirt = new Producto("T-Shirt", 40);
Producto sweater = new Producto("Sweater", 50);
}
public Cliente(String name, int numPedido) {
this.name = name;
this.numPedido = numPedido;
}
public Cliente() {
}
public String getName() {
return name;
}
public int getNumPedido() {
return (int) (Math.random() * 100);
}
public void addNewClient() {
name = JOptionPane.showInputDialog("Nombre: ");
}
public String printInfo() {
return "Nombre: " + name;
}
}
Right now I'm stuck thinking on how to make a client select a product and get that attached to him. I was thinking on making an arrayList of an arrayList but I'm sure that would complicate things. I know there is probably an easier way to connect them but I can't think of any. The option I have in mind is a method which shows numbers from 1 to 3(corresponding to each product) and when the user picks one it should return the price of the item.
Still not sure how to implement it in a way that the user can pick multiple products.
EDIT:
I also have an admin class that goes like this:
public class Admin {
private Client[] clientList;
public AdminPedidos() {
clientList = new Client[2];
}
public void AddContact() {
clienteList[0] = addProduct();
clienteList[1] = addProduct();
fillList();
}
public Cliente addProduct() {
String contactoString = JOptionPane.showInputDialog("Are you a new client? Press 1 if yes.");
if (contactoString.equals("1")) {
return new Cliente();
} else {
return new Cliente(); //just for testing
}
}
private void fillList() {
for (Client i : clientList) {
i.addNewClient();
}
}
public void printContact() {
for (Client i : clientList) {
System.out.println(i.printInfo());
}
}
}
You can have some purchaseProduct method attached to each Client.
public void purchaseProduct(Product product) { this.products.add(product); }
Then each Client you instantiate (Client client = new Client(name, id);) can add Products to his/her cart with the purchaseProduct method.
I'm assuming you are using some kind of user input method (Scanner). With that you can read the user's input of which Product they want and accordingly call the function with the right Product.
The listBuilder function doesn't quite make sense to me btw (and after your edit, it's really hard to make sense of what the Admin class should be/represent).
Edit: You would probably want to create an ArrayList<Product> which will be attached to each client, which you already have. I sense that you have a difficulty deciding where to put your actual Products. You should not put them inside your Client class for sure.
You should think about who/where they are going to be used. Probably in main right? So just instantiate them there first and then the Client could choose which one to purchase (via the method I introduced before):
client.purchaseProduct(product);

How can I calculate the sum of all elements within my JList ?

I'm creating a shopping cart simulation with a list of products that i want to add together and display the total of as they are being added to the cart basket (implemented as a jlist).
In my main class I have a button with an action listener to take items from my stocklist and add them to the basket.
scanBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
checkoutBasket.addElement(productList.getSelectedValuesList());
}
});
In addition I have a JTextField set up below the basket which I want to dynamically update with the total cost as I add items to the cart. My question is how could I go about doing this ? Thank you.
cartTotalField = new JTextField();
getContentPane().add(cartTotalField);
cartTotalField.setBounds(581, 441, 233, 28);
Cart Item Class :
import java.io.*;
public class CartItem implements Serializable {
private String barcodeNo;
private String itemName;
private String price;
public CheckoutItem() {
}
public CheckoutItem (String barno, String in, String cost) {
barcodeNo = barno;
itemName = in;
price = cost;
}
public String getBarcodeNo(){
return barcodeNo;
}
public String getItemName(){
return itemName;
}
public void setitemName(String itemName){
this.itemName = itemName;
}
public String getPrice(){
return price;
}
public String toString(){
return barcodeNo + ": " + itemName + ", " + price;
}
public Object getID() {
// TODO Auto-generated method stub
return null;
}
}
In your actionPerformed, you could do something like this (of course, this is a very naive approach to get it, you could possibly think of something better on this):
#Override
public void actionPerformed(ActionEvent evt) {
//Get the newly added list values.
JList list = productList.getSelectedValuesList();
double totalAddedValue = 0.0;
double oldCartValue = 0.0;
//Iterate to get the price of the new items.
for (int i = 0; i < list.getModel().getSize(); i++) {
CartItem item = (CartItem) list.getModel().getElementAt(i);
totalAddedValue += Double.ParseDouble(item.getPrice());
}
//Set total price value as an addition to cart total field.
//cartTotalField must be accessible here.
string cartFieldText = cartTotalField.getText();
//Check that cartTextField already contains a value.
if(cartTextField != null && !cartTextField.isEmpty())
{
oldCartValue = Double.parseDouble(cartFieldText);
}
cartTotalField.setText(String.valueOf(oldCartValue + totalAddedValue));
checkoutBasket.addElement(list);
}
UPDATE: In general, you should consider adding checks and/or exception handling for numeric conversions. A good idea would also be to change the price property to double (or int, modifying the above code accordingly) in your CartItem class.

What is wrong with this method - (Adding Elements within a Jlist)?

I'm currently in the process of creating a shopping cart simulation program. The main GUI contains two lists, one is a list of products or the inventory. (products stored within a .dat file which is automatically loaded upon launch) The other is blank and is to model my shopping basket. The idea is to be able to scan items from my inventory into the checkout basket. As this is happening i want a text field i created to dynamically update with the cost of all the items in the basket.
Below is the method for my scan button, which is supposed to perform the above :
public void actionPerformed(ActionEvent evt) {
//Get the newly added list values.
JList list = productList.getSelectedValuesList();
double totalAddedValue = 0.0;
double oldCartValue = 0.0;
//Iterate to get the price of the new items.
for (int i = 0; i < list.getModel().getSize(); i++) {
CartItem item = (CartItem) list.getModel().getElementAt(i);
totalAddedValue += Double.ParseDouble(item.getPrice());
}
//Set total price value as an addition to cart total field.
//cartTotalField must be accessible here.
string cartFieldText = cartTotalField.getText();
//Check that cartTextField already contains a value.
if(cartTextField != null && !cartTextField.isEmpty())
{
oldCartValue = Double.parseDouble(cartFieldText);
}
cartTotalField.setText(String.valueOf(oldCartValue + totalAddedValue));
checkoutBasket.addElement(list);
}
Currently however scanning the item will add it to the list but print strange results in the total. (Adds 5.5 for each item regardless of their actual value**). It will also print a line under the item name as such javax.swing.JList[,0,0,344x326,layout=java.awt.BorderLa... .
Below are the classes for my CartItem and ItemList if they may help. Thank you.
-Cart Item
import java.io.*;
public class CartItem implements Serializable {
private String barcodeNo;
private String itemName;
private String price;
public CartItem() {
}
public CartItem (String barno, String in, String cost) {
barcodeNo = barno;
itemName = in;
price = cost;
}
public String getBarcodeNo(){
return barcodeNo;
}
public String getItemName(){
return itemName;
}
public void setitemName(String itemName){
this.itemName = itemName;
}
public String getPrice(){
return price;
}
public String toString(){
return barcodeNo + ": " + itemName + ", " + price;
}
public Object getID() {
// TODO Auto-generated method stub
return null;
}
}
-ItemList
import javax.swing.DefaultListModel;
public class ItemList extends DefaultListModel {
public ItemList(){
super();
}
public void addCartItem(String barcodeNo, String itemName, String price){
super.addElement(new CartItem(barcodeNo, itemName, price));
}
public CartItem findItemByName(String name){
CartItem temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (CartItem)super.elementAt(i);
if (temp.getItemName().equals(name)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (CartItem)super.elementAt(indexLocation);
}
}
public CartItem findItemByBarcode(String id){
CartItem temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (CartItem)super.elementAt(i);
if (temp.getBarcodeNo().equals(id)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (CartItem)super.elementAt(indexLocation);
}
}
public void removeItem(String id){
CartItem empToGo = this.findItemByBarcode(id);
super.removeElement(empToGo);
}
}
You're adding the JList itself to the check out basket, and that doesn't make sense:
checkoutBasket.addElement(list);
This, javax.swing.JList[,0,0,344x326,layout=java.awt.BorderLa... . shows that something is displaying the toString() representation of the JList, likely your checkout basket.
Regarding,
Adds 5.5 for each item regardless of their actual value
I don't think your current code shows why this is happening, and you might want to create and post an mcve.
Other thoughts:
Don't use String to represent price, but rather consider a numeric field, perhaps BigDecimal if you want to be accurate for money.
You look to be mixing your view with your model too much. Try to keep them separate as possible, meaning, you should likely have some more non-GUI classes including one to represent the shopping basket, and any other nouns.

computing the total cost of bookings

id appreciate anyones help here. Below is my class that contains all my setters and getters, in my main class, ive created 3 customers and in the value parameters, i have 3 different numbers. What i need to do is find the total value of all of those values, is there any way that i can create a method (See bookingValue below) that will calculate and add the the total of each customers value parameter? Bare in mind that 3 is not a fixed number, so the method should not be affected should i choose to add in more customers. This is probably really basic but if someone could get me on the right path, that'd be great, cheers
public class Customer
{
private int identity;
private String name;
private String address;
private double value;
public Customer()
{
identity = 0;
name = "";
address = "";
value = 0.0;
}
public void setIdentity(int identityParam)
{
identity = identityParam;
}
public int getIdentity()
{
return identity;
}
public void setName(String nameParam)
{
name = nameParam;
}
public String getName()
{
return name;
}
public void setAddress(String addressParam)
{
address = addressParam;
}
public String getAddress()
{
return address;
}
public void setValue(double valueParam)
{
value = valueParam;
}
public double getCarCost()
{
return value;
}
public void printCustomerDetails()
{
System.out.println("The identity of the customer is: " + identity);
System.out.println("The name of the customer is: " + name);
System.out.println("The address of the customer is: " + address);
System.out.println("The value of the customers car is: " + value + "\n");
}
public void bookingValue()
{
//Ive tried messing around with a for loop here but i cant seem to get it working
}
}
you can create an array of object of class customer and access the value in loop...
In the main function:
customer cus[]=new customer[num];
where num can be any number as 3 in your case
then get the "value" for each customer.. and then
public double bookingValue(customer []cus, int length)
{
double total=0.0;
for(int i=0;i<length;i++)
total+=a[i].value;
return total;
}'
return total value wherever you want to use.....
As in real life, one customer doesn't know anything about the other customers. If you would ask a customer in a store how much all customers spent, he will just look as confused as others reading this question.
I'd suggest implementing some CustomerManager, or Bookkeeper which hold all the customers internally (in a List for example). This CustomerManager needs to have methods to add and remove customers, the getBookingValue() method which loops over all customers in the CustomerManager's customers List and returns the total value and, if you please, some other comfort methods.
As an example:
public interface CustomerManager {
public void addCustomer(Customer customer);
public void removeCustomer(Customer customer);
public List<Customer> getCustomersByDate(long from, long to);
public double getBookingValue();
public double getBookingValue(List<Customer> customerList);
public List<Customer> getByAddress(String address);
public List<Customer> getByName(String name);
}

Categories

Resources