Java - Scanning Items in an ArrayList - java

I have a class which creates a 'Purchase' object. This object can be recorded to an ArrayList 'purchaseList' using the recordItem() method. However, I want to create a function that can return a specific Purchase object given an itemNo integer, I have shown my code so far in getPurchase() but am having trouble getting it working.
public class Purchase {
private String name;
private double price;
private int itemNo;
private int sort;
private ArrayList purchaseList = new ArrayList();
public Purchase(String name, double price, int itemNo, int sort) {
this.name = name;
this.price = price;
this.itemNo = itemNo;
this.sort = sort;
}
public void recordItem(int itemNumber, String description, double unitPrice, int sort) {
Purchase newPurchase = new Purchase(description, unitPrice, itemNumber, sort);
purchaseList.add(newPurchase);
}
public int getItemNo() {
return itemNo;
}
public Purchase getPurchase(int itemNumber) {
for(int i = 0; i < purchaseList.size(); i++) {
if(purchaseList[i].getItemNo() == itemNumber) {
return purchaseList[i];
}
else return 0;
}
}
}

purchaseList[i] is valid when you work with arrays.
When working with List objects, to retrieve the ith element, you have to invoke the List.get(int index) method. Like this:
purchaseList.get(i)
And so, your method has to be refactored to:
public Purchase getPurchase(int itemNumber) {
for(int i = 0; i < purchaseList.size(); i++) {
if(purchaseList.get(i).getItemNo() == itemNumber) {
return purchaseList.get(i);
}
else return 0;
}
}
Also, in order to avoid casting from Object to Purchase, you have to make your List generic.
private List<Purchase> purchaseList = new ArrayList<Purchase>();
This way the compiler will ensure that the objects you add to the list are of type Purchase and will not force you to cast them to something specific when being got.

Change your purchaseList[i].getItemNo() to purchaseList.get(i).getItemNo()

Your getPurchase() method logic is incorrect. You shouldn't exit after the first condition is not met.
Try changing it like this:
// Change the declaration like this
private List<Purchase> purchaseList = new ArrayList<Purchase>();
// And change the method like this:
public Purchase getPurchase(int itemNumber) {
for(Purchase purchase : purchaseList) {
if(purchase.getItemNo() == itemNumber) {
return purchase;
}
}
return null;
}
Also recordItem() and getPurchase() don't look like they belong inside the Purchase class.

Related

how to add/remove multiples of objects from an array list

I am trying to build an ArrayList that will contain objects. when i add an object to the list i want it to first check the array list for that object. and if it finds it i want it to increase a quantity variable in that object and not create a new object in the list. and then vice versa when removing objects. I have accomplished a way that works when removing an object. But i dont think i fully understand the methods in the arraylist or the logic when creating and arraylist of objects. as when i use .contains or .equals im not getting the desired effect.
public class ItemBag {
private ArrayList<Item> inventory = new ArrayList<Item>();
public ItemBag() {
}
public void addItem(Item objName, int quantity) {
if (inventory.contains(objName)) {
System.out.println("if statement is true!");
int i = inventory.indexOf(objName);
inventory.get(i).setQuantity(inventory.get(i).getQuantity() + quantity);
} else {
inventory.add(objName);
objName.setQuantity(quantity);
}
}
public void removeItems(String itemName, int quantiy) {
for (int i = 0; i < inventory.size(); i++) {
if (inventory.get(i).name() == itemName) {
inventory.get(i).setQuantity(inventory.get(i).getQuantity() - quantiy);
if (inventory.get(i).getQuantity() <= 0) {
inventory.remove(inventory.get(i));
}
}
}
}
public void showInventory() {
for (int i = 0; i < inventory.size(); i++) {
System.out.println(inventory.get(i).name() + " : " + inventory.get(i).getQuantity());
}
}
then when creating the itemBag in another object i am writing
ItemBag merchantItems = new ItemBag();
public void merchantBob() {
merchantItems.addItem(new HealthPotion() ,3);
merchantItems.showInventory();
System.out.println("add 1");
merchantItems.addItem(new HealthPotion(),1);
merchantItems.showInventory();
Items class
package Items;
public abstract class Item {
private int quantity = 0;
public Item() {
}
public abstract String name();
public abstract int cost();
public abstract String type();
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
HealthPotion Class
public class HealthPotion extends Potions {
protected int addHealth = 10;
#Override
public int drinkPotion() {
return addHealth;
}
#Override
public String name() {
return "Health Potion";
}
#Override
public int cost() {
return 5;
}
#Override
public String type() {
return "Potion";
}
}
The .contains() method would iterate through the list and use .equals() method to compare each element and check if the provided object exists in the list.
.equals() method would compare the object reference (unless .equals() is overridden) to check if the objects are same.
For reference: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#contains-java.lang.Object-
You can override the .equals() method to compare the values of the provided object in the following way:
public abstract class Item {
private int quantity = 0;
public Item() {
}
public abstract String name();
public abstract int cost();
public abstract String type();
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
#Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Item providedItem = (Item) object;
return name == providedItem.name
&& cost == providedItem.cost
&& type == providedItem.type;
}
}
This should work

how to sort a list by the second parameter in java?

How do I sort the second parameter (double) of the ParqueDistancia object and print in android studio? Someone can help me?
..................................................................................................
**********Class FragmentMap*******
ArrayList<ParqueDistancia> listaLocalizacaoParques = new ArrayList<ParqueDistancia>();
ParqueDistancia muma = new ParqueDistancia("A",0.5);
ParqueDistancia artes = new ParqueDistancia("B",60.5);
ParqueDistancia estadio = new ParqueDistancia("B",41.6);
listaLocalizacaoParques.add(muma);
listaLocalizacaoParques.add(artes);
listaLocalizacaoParques.add(estadio);
******************* Object **************************
public class ParqueDistancia {
private String nomeParque;
private Double Distancia;
public ParqueDistancia(String nomeParque, Double distancia) {
nomeParque = nomeParque;
Distancia = distancia;
}
public String getNomeParque() {
return nomeParque;
}
public void setNomeParque(String nomeParque) {
this.nomeParque = nomeParque;
}
public Double getDistancia() {
return Distancia;
}
public void setDistancia(Double distancia) {
Distancia = distancia;
}
}```
You can use the sort method on the list and pass the comparator that compares based on second property private Double Distancia;
listaLocalizacaoParques.sort(Comparator.comparingDouble(ParqueDistancia::getDistancia));
I have couple of recommendations, first one always start the variable name with lower case letter
private Double distancia;
And second, use this keyword in constructor
public ParqueDistancia(String nomeParque, Double distancia) {
this.nomeParque = nomeParque;
this.distancia = distancia;
}
Override compareTo method
#Override
public int compareTo(ParqueDistancia obj) {
/* For Ascending order*/
return this.Distanscia>obj.getDistansia();
/* For Descending order do like this */
//return this.Distanscia<obj.getDistansia();
}
and where you want to sort
Collections.sort(arraylist);

JOptionPane not displaying all items from ArrayList

I am trying to write a program that will create a food order consisting of food items displayed from a menu. Each item is selected and given a certain quantity. I want to display the items that I select in a JTextField but it has not been working correctly.
There are a few problems that I have ran into and cannot seem to figure out,
The JOptionPane is supposed to display all of the items that I added to the deli arraylist, but it only displays the first one which is Nachos.
My getTotalPrice method is not properly calculating the cost and I'm not entirely sure why.
I want the program to determine if an item is already present in the Arraylist and add to the quantity if it does, and if not then add a new entry to the arraylist. However, it always adds a new item, regardless of if it exists already.
The following is my are all of my class files.
import java.util.ArrayList;
public class Menu {
private final ArrayList<Item> menu;
public Menu() {
menu = new ArrayList<>();
}
public void addItem(Item item) {
menu.add(item);
}
public Item getItem(int itemNo) {
if (menu.size() > itemNo) {
return menu.get(itemNo);
}
return null;
}
#Override
public String toString() {
for (int i = 0; i < menu.size(); i++) {
return String.format("%s: %s \n",i+1, menu.get(i));
}
return null;
}
}
public class Item {
private final String name;
private final double price;
public Item(String name, double price) {
this.name = name;
this.price = price;
}
public double getPrice() {
return price;
}
#Override
public String toString() {
return String.format("Name %s # Price $%s", name, price);
}
public boolean equals(Item item) {
return item.name.equals(item.name);
}
}
public class ItemQty {
private final Item item;
private final int quantity;
public ItemQty(Item item, int quantity) {
this.item = item;
this.quantity = quantity;
}
public Item getItem() {
return item;
}
public int getQuantity() {
return quantity;
}
#Override
public String toString() {
return String.format("%s - %s\n", quantity, item);
}
public boolean equals(ItemQty itemQty) {
return itemQty.getItem().equals(itemQty.getItem());
}
}
import java.util.ArrayList;
public class Order {
private final ArrayList<ItemQty> order;
public Order() {
order = new ArrayList<>();
}
public void addToOrder(ItemQty itemQty) {
if (order.contains(itemQty)) {
int amount = itemQty.getQuantity();
amount += 1;
}
else
order.add(itemQty);
}
public double getTotalPrice() {
for (int index = 0; index < order.size(); index++) {
double price = order.get(index).getItem().getPrice();
int quantity = order.get(index).getQuantity();
double sum = price * quantity;
return sum;
}
return 0;
}
#Override
public String toString() {
String str = "";
for (int index = 0; index < order.size(); index++) {
str += order.get(index).toString() + "\n\n";
}
return str;
}
}
Any help or critiques would be appreciated
My getTotalPrice method is not properly calculating the cost and I'm not entirely sure why.
This is due to the fact that you're returning the value of sum only after the first iteration of your loop
public double getTotalPrice() {
for (int index = 0; index < order.size(); index++) {
double price = order.get(index).getItem().getPrice();
int quantity = order.get(index).getQuantity();
double sum = price * quantity;
return sum;
}
return 0;
}
Something like...
public double getTotalPrice() {
double sum = 0;
for (Order item : order) {
double price = item.getItem().getPrice();
int quantity = item.getQuantity();
sum += (price * quantity);
}
return sum;
}
would work better
The JOptionPane is supposed to display all of the items that I added to the deli arraylist, but it only displays the first one which is Nachos.
Since there is no JOptionPane in your code, it's impossible to know what the issue might be
I want the program to determine if an item is already present in the Arraylist and add to the quantity if it does, and if not then add a new entry to the arraylist. However, it always adds a new item, regardless of if it exists already.
Okay, this is a lot more difficult, because you code doesn't really provide enough support to do it.
There's no way for your code to update the quantity information after the ItemQty is created, you will need to supply a setter of some kind to perform this action (or a add method, to which you pass another ItemQty and it does the job for you)
First, I'd add a new method to ItemQty
public class ItemQty {
//...
public void add(int quantity) {
this.quantity += quantity;
}
}
This just makes it possible to increase the quantity.
Second, I'd change the Order#addToOrder, I'd make it so you had to pass an Item and a quantity to it (other classes don't need to make a ItemQty object in this case). In this method, I'd search for a matching item and either update it or add it to the order.
public class Order {
//...
public void addToOrder(Item item, int quantity) {
List<ItemQty> matches = order.stream().filter((itemQty) -> {
return itemQty.getItem().equals(item);
}).collect(Collectors.toList());
if (matches.size() > 0) {
matches.get(0).add(quantity);
} else {
order.add(new ItemQty(item, quantity));
}
}
Okay, that might have you scratching your head, it does me, but basically, it's just a fancy pancy way for saying...
public void addToOrder(Item item, int quantity) {
ItemQty match = null;
for (ItemQty check : order) {
if (check.getItem().equals(item)) {
match = check;
break;
}
}
if (match != null) {
match.add(quantity);
} else {
order.add(new ItemQty(item, quantity));
}
}

Trying to make a 2d array program to store a list of Car objects

Struggling with a little project I've set myself to learn Java. My goal is to create a program to store a list of Car objects. Then to allow the user to search for a particular car and output all of them if they exist. The car object should contain model name, registration number, vin and colour. Here is what I have so far:
package carObjects;
public class cars {
public static int length;
private String modelName;
private String carColour;
private int regNumber;
private int vin;
public cars(String string, String string2, int i) {
}
public String toString() {
return "Model Name: " + modelName + "Registration Number: " + regNumber
+ "Vin" + vin + "Car Colour: " + carColour;
}
public String getLast() {
return modelName;
}
}
for (int i = 0; i < cars.length; i++) {
cars[i] = new cars("A", "B", 10);
}
for (cars p : cars) {
System.out.println(p.getLast());
}
}
}
Here are some of the things you would need to do:
Since you want to allow searching, you will need to expose accessors to the properties which you would like the user to search for. For instance, if you want to allow users to search by model, you will need to expose the model property. You seem to be doing this through the getLast() method, however, the name is confusing.*
The problem with this code: for (int i = 0; i < cars.length; i++) {
cars[i] = new cars("A", "B", 10);
}
Is that it is creating a series of identical objects. You could use the value of i to provide some dummy, changing values. This will allow you to test that your search is indeed working.
Constructor names should start with an upper case, just like class names.
cars(String string, String string2, int i): Please provide meaningful names to your variables. This will make your code easier to read.
You will need to assign the variables you are getting through your constructor. As is, at the moment your fields will not be initialized to what you are providing.
To create a 2D array, you will need to use the following syntax: Car[][] carArr = new Car[5][5]. This will create a 5x5 array of type car. To iterate over it, you will need to use a nested loop:
for(int i = 0; i < carrArr.length; i++) {
for (int j = 0; j < carrArr[i].lenght;j++) {
...
}
}
* The usage of getters and setters allow you to control which object properties are exposed and how can users interact with them.
The best would be to separate your exercise in two different classes:
class Car {
private String modelName;
private String carColour;
private int regNumber;
private int vin;
public int getVin() {
return vin;
}
public void setVin(int vin) {
this.vin = vin;
}
// other getter/setter
#Override
public String toString() {
return "Car: " + getVin();
}
#Override
public int hashCode() {
return vin;
}
#Override
public boolean equals(Object obj) {
return (obj != null)
&& (obj instanceof Car)
&& ((Car) obj).getVin() == this.getVin();
}
}
CarSet class has the searching methods:
class CarList extends HashSet<Car> {
public Car serarchByVin(int vin) {
List<Car> list = new ArrayList<>(this);
for (Car c : list) {
if (c.getVin() == vin) {
return c;
}
}
return null;
}
public CarSet searchByModel(String model) {
CarSet result = new CarSet();
List<Car> list = new ArrayList<>(this);
for (Car c : list) {
if (c.getModelName()== model) {
result.add(c);
}
}
return result;
}
#Override
public String toString() {
String result = "carList: ";
for (Car c : this) {
result += c;
}
return result;
}
}

How can I use objects in an ArrayList to be able to add or remove them from other bit of storage Java

I need to be able to create a set of inventories which are able to store objects that I choose. I have an ArrayList of the objects I need to be able to store in these inventories which have an "item number", "description" and "price".
My question is, what can I use to create these inventories so the user is able to add or remove items (which all come from the ArrayList of items) into them. The only way I can think it would work is by creating another ArrayList being the inventories but I wouldn't know how to add/remove the objects to them seeing as they're in the ArrayList
I have a main method which is where my ArrayList is and an item class with a constructor, getters, setters and toString.
You can add or remove class objects in ArrayList. Following is an example:
import java.util.ArrayList;
public class InventoryHandler {
public static void main(String[] args) {
Inventory inv1 = new Inventory(1,"item1",10.1);
Inventory inv2 = new Inventory(2,"item2",20.1);
Inventory inv3 = new Inventory(3,"item3",30.1);
ArrayList<Inventory> invs = new ArrayList<Inventory>();
//Adding objects
invs.add(inv1);
invs.add(inv2);
invs.add(inv3);
System.out.println("After adding objects");
for(Inventory inv: invs) {
System.out.println("Item: "+inv.getItemNumber()+" Desc: "+
inv.getItemDescription()+" Price: "+inv.getItemPrice());
}
//Removing objects
invs.remove(inv2);
System.out.println("After removing a object");
for(Inventory inv: invs) {
System.out.println("Item: "+inv.getItemNumber()+" Desc: "+
inv.getItemDescription()+" Price: "+inv.getItemPrice());
}
}
}
class Inventory {
private int itemNumber;
private String itemDescription;
private double itemPrice;
public Inventory(int itemNumber, String itemDescription, double itemPrice) {
this.itemNumber = itemNumber;
this.itemDescription = itemDescription;
this.itemPrice = itemPrice;
}
public int getItemNumber() {
return this.itemNumber;
}
public String getItemDescription() {
return this.itemDescription;
}
public double getItemPrice() {
return this.itemPrice;
}
public void setItemNumber(int newItemNumber) {
this.itemNumber = newItemNumber;
}
public void setItemDescription(String newItemDescription) {
this.itemDescription = newItemDescription;
}
public void setItemPrice(double newItemPrice) {
this.itemPrice = newItemPrice;
}
}

Categories

Resources