i'm new to java and I am having problems adding my array objects to my list. I have already checked the topics in this forum but can't find something similar to my problem.
I have already made a class called Item that will save information about an item to be sold, and it has 4 instance variables id, desc, cost, quantity. And then I have a Sales class which has my main method. Basically what I want to do is build an array of objects from my Item class and hard code my data(which I have already created, i'm not sure if I did it right though).
I have created an ArrayList and what I want to do now is add the 5 objects from the array that I created into the list.
This is my Item class
public class Item {
private String itemID;
private String desc;
private double cost;
private int quantity;
public Item() {
itemID="";
desc="";
cost=0;
quantity=0;
}
public Item(String id, String d, double c, int q) {
itemID = id;
desc = d;
cost = c;
quantity = q;
}
/**
* #return the itemID
*/
public String getItemID() {
return itemID;
}
/**
* #param itemID the itemID to set
*/
public void setItemID(String itemID) {
this.itemID = itemID;
}
/**
* #return the desc
*/
public String getDesc() {
return desc;
}
/**
* #param desc the desc to set
*/
public void setDesc(String desc) {
this.desc = desc;
}
/**
* #return the cost
*/
public double getCost() {
return cost;
}
/**
* #param cost the cost to set
*/
public void setCost(double cost) {
this.cost = cost;
}
/**
* #return the quantity
*/
public int getQuantity() {
return quantity;
}
/**
* #param quantity the quantity to set
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Item [itemID=" + itemID + ", desc=" + desc + ", cost=" + cost
+ ", quantity=" + quantity + "]";
}
}
And my Sales class:
import java.util.*;
public class Sales {
/**
* #param args
*/
public static void main(String[] args) {
int i;
Item[] items = new Item[5];
for(i = 0; i < items.length; i++)
{
items[i]= new Item(); // create array
}
//hard-coded values of id, desc, cost, qty
items[0].setItemID("PN250");
items[1].setItemID("ER100");
items[2].setItemID("PP150");
items[3].setItemID("MK200");
items[4].setItemID("PN300");
items[0].setDesc("Pen");
items[1].setDesc("Eraser");
items[2].setDesc("Paper");
items[3].setDesc("Marker");
items[4].setDesc("Pen");
items[0].setCost(1.50);
items[1].setCost(1.25);
items[2].setCost(3.75);
items[3].setCost(2.50);
items[4].setCost(2.25);
items[0].setQuantity(0);
items[1].setQuantity(175);
items[2].setQuantity(310);
items[3].setQuantity(75);
items[4].setQuantity(450);
double total = 0;
for(Item d : items)
{
System.out.print(d.getItemID());
System.out.print("\t" + d.getDesc());
System.out.print("\t" + d.getCost());
System.out.println("\t" + d.getQuantity());
}
List<Item> obj;
obj = new ArrayList<Item>();
}
}
You could add the array into your list with the following:
obj.addAll(Arrays.asList(items));
You can use:
for (i = 0; i < items.length; i++)
{
obj.add(items[i]);
}
but why not add the items as soon as they are created & populated?
instead of creating an array at the beginning of your function, create an arrayList and add objects to it using the put method.
Also, you should think of making your objects immutables and pass their attributes to their constructor instead of calling the setter for each attribute
Related
I am working on a project where I create "products" that are made up of ObservableList "parts".
Main screen
I create a product and add a part to it. You can see here, I add part "Screwdriver" to product TESTPROD1.
Creating Product
Next, I create TESTPROD2 and add part "Wrench" to it.
Creating Second Product
Finally, I go back to modify the original product (TESTPROD1), which should only contain "Screwdriver", but it contains both "Screwdriver" and "Wrench".
Modify TESTPROD1
Here is where I am creating the product when the "Save" button is pressed.
private void addProductSaveHandler(ActionEvent event) throws IOException {
Product p = new Product(
Integer.parseInt(addProductIdTextField.getText()),
addProductNameTextField.getText(),
Double.parseDouble(addProductPriceTextField.getText()),
Integer.parseInt(addProductInvTextField.getText()),
Integer.parseInt(addProductMinTextField.getText()),
Integer.parseInt(addProductMaxTextField.getText())
);
Inventory.addProduct(p);
for (Part addedPs : tableSelectedParts){
//Inventory.lookupProduct(p.getId()).addAssociatedPart(addedPs);
Inventory.lookupProduct(Integer.parseInt(addProductIdTextField.getText())).addAssociatedPart(addedPs);
}
tableSelectedParts.clear();
//Return to main screen
stage = (Stage)((Button)event.getSource()).getScene().getWindow();
scene = FXMLLoader.load(getClass().getResource("/view/MainForm.fxml"));
stage.setScene(new Scene(scene));
stage.show();
}
#FXML
private void addPartHandler(ActionEvent event) {
tableSelectedParts.add(addProductAllPartsTable.getSelectionModel().getSelectedItem());
}
public class Inventory {
private static ObservableList<Part> allParts = FXCollections.observableArrayList();
private static ObservableList<Product> allProducts = FXCollections.observableArrayList();
public static void addPart(Part newPart){
allParts.add(newPart);
}
public static void addProduct(Product newProduct){
allProducts.add(newProduct);
}
public static Part lookupPart(int partId){
return allParts.get(partId);
}
public static Product lookupProduct(int productId){
int productLocation = 0;
for (int i = 0; i < allProducts.size(); i++){
if (allProducts.get(i).getId() == productId){
productLocation = i;
}
}
return allProducts.get(productLocation);
}
public static ObservableList<Product> lookupProduct(String productName){
ObservableList<Product> matchingProduct = FXCollections.observableArrayList();
for (int i = 0; i < allProducts.size(); i++){
if (allProducts.get(i).getName().contains(productName)){
matchingProduct.add(allProducts.get(i));
}
}
return matchingProduct;
}
}
public class Product {
private static ObservableList<Part> associatedParts = FXCollections.observableArrayList();
private int id;
private String name;
private double price;
private int stock;
private int min;
private int max;
public Product(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;
}
/**
* #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;
}
public static void addAssociatedPart(Part part){
associatedParts.add(part);
}
public boolean deleteAssociatedPart(Part part){
associatedParts.remove(part);
//not sure about this below - come back later
return false;
}
public static ObservableList<Part> getAllAssociatedParts(){
return associatedParts;
}
}
For some reason, creating a new product overwrites the ObservableList of parts associated with the previous product. I've been trying to figure out why this is for hours. Any help would be appreciated.
Your class Product declares associatedParts as being static. This means there is only one list per JVM, rather than one list per product.
In other words: remove the static keyword and each product will have its own associated parts.
It's a code about a 'shopping cart' that can hold items of a class called 'item'. I had to complete the class 'item' and write another class 'discount' that can reduces the price of an item.
import java.util.ArrayList;
public class Shoppingcart extends Item {
// all shopping carts:
private ArrayList<Shoppingcart> allshoppingcart = new ArrayList<Shoppingcart>();
//Items in the shopping cart:
private ArrayList<Item> content = new ArrayList<Item>();
// Counter for shopping carts
private static int number;
/**
* Constructor
*/
public Shoppingcart() {
allshoppingcart .add(this);
this.number = number ;
this.number++;
}
/**
* load something in Shoppingcart
*/
public void load(Item i) {
this.content.add(i);
}
/**
* Sum of all items loaded in the shoppingcart
*
* #return sum of the content in the shopping cart
*/
public double sumShoppingCart() {
double sum = 0.0;
for (Item i : content) {
sum = sum + item.getPrice();
}
return sum;
}
}
The class 'item' so I can store two different types in the arraylist.
public class Item {
// normal price of item
protected double price;
// Name of product
protected String name;
/**
* setter for price and name
*/
public void setPB(String name, double price) {
this.name = name;
this.price = price;
}
/**
* getter for price
*/
public double getPrice() {
return this.price;
}
/**
* getter for the name
*/
public String getName() {
return this.name;
}
}
The class 'discount' to reduce an item for an example like a sale (special-offer).
public class Discount extends Item
{
// instance variables - replace the example below with your own
public Discount()
{
// initialise instance variables
}
public void makeSale(int percent){
percent =(100-percent)/100;
price = w.getPrice()*percent;
}
}
A test class
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Item> content = new ArrayList<>();
Item item = new Item();
Item item1 = new Item();
Item item2 = new Item();
item.setPB("Steak", 100.00);
item1.setPB("Water", 200.00);
item2.setPB("Groceries", 300.00);
content.add(item);
content.add(item1);
content.add(item2);
System.out.println("The item has the value : " + item.getPrice() + " and the name: " + item.getName());
System.out.println("There are : " + content.size() + " Item(s) in the shopping cart.");
}
}
How do I access an item and reduce it for a sale?
Thank you
This is a typical OOP exercise. You want to access two different types in a single collection. To do so they both need to have the same interface or parent.
If you use an Abstract base class you can use the following example.
First lets make an abstract Item class:
abstract class Item {
protected double price;
protected String name;
public Item(double price, String name) {
this.price = price;
this.name = name;
}
public double getPrice() {
return this.price;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setPrice(double price) {
this.price = price;
}
abstract void discount(double amount);
}
and two classes that extend from this base class:
class Food extends Item {
public Food(double price, String name) {
super(price, name);
}
#Override
void discount(double amount) {
this.price -= amount;
}
}
class Bevarage extends Item {
public Bevarage(double price, String name) {
super(price, name);
}
#Override
void discount(double amount) {
this.price -= amount;
}
}
Now lets make a class discount that has a List items that can discount both items.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Discount {
public void printAllContent(List<Item> items) {
items.forEach(item -> System.out.printf("name = %s, price = %.00f \n", item.getName(), item.getPrice()));
}
public static void main(String[] args) {
Discount card = new Discount();
List<Item> items = Arrays.asList(
new Food(3.0, "burgers"), new Food(9.0, "tomato"), new Food(8.0, "fries"),
new Bevarage(9.0, "cola"), new Bevarage(12.0, "water"), new Food(2.0, "beer")
);
card.printAllContent(items);
for (Item item : items) {
item.discount(1.0);
}
card.printAllContent(items);
// if you want to do different discounts for different items
for(Item item: items) {
if (item instanceof Bevarage) {
item.discount(2.0);
} else {
item.discount(1.0);
}
}
card.printAllContent(items);
}
}
java.util.List has these functions get(index) and set(index, object), which you could use:
//1. get your item
int index = 0;
Item item=content.get(index);
//2. create your discount
Discount discount=new Discount();
// Fill/process your discount object with the appropriate data
//3. replace the item with the discount in the list
content.set(index,discount);
This is an Object Oriented program with two classes Catalog and Products that reads a file that contains the product name, quantity, and price, adds them to a list array, and calculate the total Price of the items. Everything works with my program except that it has a toString method that when I ran the program it prints something like this #445ea7e I think this happens because the addProducts() and getProducts(String name) on the Catalog class has to do something with the toString() and I don't know how to connect them to work.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Catalog{
private static int MAX_ITEMS = 10;
/**
* List of Products objects.
*/
private Products[] list;
private int nextItem;
/**
* Default constructor
*/
public Catalog(){
list = new Products[MAX_ITEMS];
nextItem = 0;
}
/**
* Adds an item to the list
*/
public void addProducts (String name, int quantity, double price){
**//I tried this: list[nextItem] = new Products(name, quantity, price);
//but I'm not sure if that's ok.**
}
/**
* 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
*/
public Products getProducts(String name){
**//search a list for string equality using the name of the product and returns 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.println(toString()); **I don't know how to call toString**
System.out.println();
System.out.format("Total Price = %9.2f\n", catalog.getTotalPrice());
}
}
This is the Products class with the toString() method.
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(){
String s=null;
s+=getName();
s+=s + " ";
s+=getQuantity();
s+=s + " ";
s+=getPrice();
return s;
}
}
This is the file with the Products information
Football 2 15.50
ChapStick 1 3.87
Book 4 10.00
You add toString() to your Catalog class as Product class :
public class Catalog {
private static int MAX_ITEMS = 10;
/**
* List of Products objects.
*/
private Products[] list;
private int nextItem;
// your old code here
// new code
#Override
public String toString() {
return "this is a catalog";
}
}
You call catalog.toString():
public static void main(String[] args)
throws FileNotFoundException {
Catalog catalog= new Catalog();
catalog.loadList(args[0]);
System.out.println();
//System.out.println(toString()); **I don't know how to call toString**
// use this line
System.out.println(catalog.toString());
System.out.println();
System.out.format("Total Price = %9.2f\n", catalog.getTotalPrice());
}
In your toString() method of Product class. you should change initialize variable from s=null; to s="";. Here is sample :
public String toString(){
String s="";
s+=getName();
s+=s + " ";
s+=getQuantity();
s+=s + " ";
s+=getPrice();
return s;
}
Hope this help :)
In your toString() method (in products class), change
String s = null;
to
String s = "";
Also, you have to make a toString method for the Catalog class in order to call it.
An example toString method for catalog class can be:
public String toString(){
String toReturn = "";
for(Products current: list){
toReturn+=current.toString()+"\n";
}
return toReturn;
}
Then if main just call, System.out.println(catalog.toString());
Try adding override to your toString method this might be the solution base on your current output.
#Override
public String toString(){
String s=null;
s+=getName();
s+=s + " ";
s+=getQuantity();
s+=s + " ";
s+=getPrice();
return s;
}
I'm still fairly new in learning Java and I'm in need of a way to put every object that is constructed from a certain class into an ArrayList that I can access later.
Here is my Item class:
import java.util.ArrayList;
import java.util.*;
public class Item
{
private String name;
private int quantity;
private ArrayList<Item> allItems = new ArrayList<Item>(); //the ArrayList I'm trying to fill with every Item object
/**
* Constructs an item of a given name and quantity
* #param name Item name
* #param quantity How much of an item the player has
*/
public Item(String name, int quantity)
{
this.name = name;
this.quantity = quantity;
}
/**
* #return Item name
*/
public String getItemName()
{
return name;
}
/**
* #return Quantity of the item
*/
public int getQuantity()
{
return quantity;
}
/**
* #return A list of items that have a quantity > 0
*/
public ArrayList<Item> getInventory()
{
ArrayList<Item> inventory = new ArrayList<Item>();
for(Item i : allItems)
{
if(i.getQuantity() > 0)
inventory.add(i);
}
return inventory;
}
}
How can I add an Item object to allItems every time one is constructed?
First, the arraylis must be static so it is shared between all the instances.
Otherwise, you would have a different variable per instance.
More info on instance/class members here.
private String name;
private int quantity;
private static ArrayList<Item> allItems = new ArrayList<Item>();
Then, you can add the created instance in the constructor, refering to it as 'this'.
About the 'this' keyword.
public Item(String name, int quantity)
{
this.name = name;
this.quantity = quantity;
allItems.add(this);
}
You certainly want one list for all items, and not every item to carry around and maintain its own copy list of all items. When that's your intention, you should define the list as static:
private static ArrayList<Item> allItems = new ArrayList<Item>()
A static variable is shared by all instances of the class.
In the constructor of Item, just add this to the list of all items.
allItems.add(this);
You need a static List and then you can use the class constructor to add this object into the list.
import java.util.ArrayList;
import java.util.*;
public class Item
{
private String name;
private int quantity;
private static ArrayList<Item> allItems = new ArrayList<Item>(); //the ArrayList I'm trying to fill with every Item object
/**
* Constructs an item of a given name and quantity
* #param name Item name
* #param quantity How much of an item the player has
*/
public Item(String name, int quantity)
{
this.name = name;
this.quantity = quantity;
allItems.add(this);
}
/**
* #return Item name
*/
public String getItemName()
{
return name;
}
/**
* #return Quantity of the item
*/
public int getQuantity()
{
return quantity;
}
/**
* #return A list of items that have a quantity > 0
*/
public static ArrayList<Item> getInventory()
{
ArrayList<Item> inventory = new ArrayList<Item>();
for(Item i : allItems)
{
if(i.getQuantity() > 0)
inventory.add(i);
}
return inventory;
}
}
One possible solution would be to declare the items list as static like this:
public static List<Item> allItems = new ArrayList<Item>();
afterwards you could access it using the following snippet:
Item.allItems // example would be System.out.println(Item.allItems)
Additionally within your constructor you will need the following code:
public Item(String name, int quantity) {
this.name = name;
this.quantity = quantity;
this.allItems.add(this);
}
BUT use this approach with caution, since it will add to list every single item created, what could lead to a possible memory leak.
In an application we have a Boarding table having ( boarding_id + invoice_no + item_id ) as key. A Boarding_tmp table with same table structure as Boarding. We are loading Boarding_tmp from a csv file (pipe separator column values)
We have a Boarding java bean with all columns. Let's say we have two list -
1. boardingList with all active records in Boarding table
2. boardingTmpList with all records in Boarding_Tmp table
I need to compare these two list to implement below scenario -
We Need to compare Boarding table with Boarding_tmp table and need to do following (No SQL joins. We have to perform this on object level) -
a. All records which are in Boarding_tmp but not in Boarding table should be inserted in Boarding table (means they are new records)
b. All records which are in Boarding but not in Boarding_tmp table should be mark as deactivated in Boarding table (we have a active column in Boarding table)
Here in Boarding.java -
public class Boarding implements Comparable {
private String bordingId;
private String itemId;
private String invoiceNo;
private String itemName;
private long qty;
private double price;
/**
* #return the bordingId
*/
public String getBordingId() {
return bordingId;
}
/**
* #param bordingId
* the bordingId to set
*/
public void setBordingId(String bordingId) {
this.bordingId = bordingId;
}
/**
* #return the itemId
*/
public String getItemId() {
return itemId;
}
/**
* #param itemId
* the itemId to set
*/
public void setItemId(String itemId) {
this.itemId = itemId;
}
/**
* #return the invoiceNo
*/
public String getInvoiceNo() {
return invoiceNo;
}
/**
* #param invoiceNo
* the invoiceNo to set
*/
public void setInvoiceNo(String invoiceNo) {
this.invoiceNo = invoiceNo;
}
/**
* #return the itemName
*/
public String getItemName() {
return itemName;
}
/**
* #param itemName
* the itemName to set
*/
public void setItemName(String itemName) {
this.itemName = itemName;
}
/**
* #return the qty
*/
public long getQty() {
return qty;
}
/**
* #param qty
* the qty to set
*/
public void setQty(long qty) {
this.qty = qty;
}
/**
* #return the price
*/
public double getPrice() {
return price;
}
/**
* #param price
* the price to set
*/
public void setPrice(double price) {
this.price = price;
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((bordingId == null) ? 0 : bordingId.hashCode());
result = prime * result
+ ((invoiceNo == null) ? 0 : invoiceNo.hashCode());
result = prime * result + ((itemId == null) ? 0 : itemId.hashCode());
return result;
}
#Override
public int compareTo(Object o) {
if (this == o) {
return 0;
}
if (o == null) {
return 1;
}
if (getClass() != o.getClass()) {
return 1;
}
Boarding other = (Boarding) o;
if (bordingId == null) {
if (other.bordingId != null) {
return 1;
}
} else if (!bordingId.equals(other.bordingId)) {
return 1;
}
if (invoiceNo == null) {
if (other.invoiceNo != null) {
return 1;
}
} else if (!invoiceNo.equals(other.invoiceNo)) {
return 1;
}
if (itemId == null) {
if (other.itemId != null) {
return 1;
}
} else if (!itemId.equals(other.itemId)) {
return 1;
}
return 0;
}
}
Please help. Thanks.
You can try Collections Util library. They have very useful methods for the scenario you depicted.
That's easily achivable with use of List#retainAll method.
javadoc is here
You should be able to do the following:
List<Boarding> insertBoarding = new ArrayList(boardingTmpList);
insertBoarding.removeAll(boardingList);
// insert all elements in insertBoarding to the table
List<Boarding> deactivateBoarding = new ArrayList(boardingList);
deactivateBoarding.removeAll(boardingTmpList);
// deactivate all elements in deactivateBoarding in the table
Assuming your equality tests work, this should yield correct results.
NOTE: You will have to override the equals method for this to work properly.