Not able to iterate items from itemSet - java

hey guys am not able iterate or get items from ItemSet following is my code
Item class
public class Item {
private String id;
private int count;
private String name;
public int getcount() {
return this.count;
}
public Item(String name) {
this.name=name;
this.id = "";
}
public Item(String id, String name) {
this.name=name;
this.id=id;
}
public Item(int count) {
this.count=count;
}
public String getItemName() {
return this.name;
}
public String getItemId() {
return this.id;
}
public Item returnItems(ItemSet itemset) {
Item item=null;
return item;
}
}
ItemSet Class holds List of items
public class ItemSet {
private List<Item> hold;
ItemSet(Item item) {
hold = new ArrayList<Item>();
this.hold.add(item);
}
ItemSet() {
//throw new UnsupportedOperationException("Not yet implemented");
}
public List<Item> getItemSet() {
return this.hold;
}
public void addItems(Item item) {
hold = new ArrayList<Item>();
this.hold.add(item);
}
}
This is my Transaction class holds list of ItemSets
public class Transaction {
private List<ItemSet> trans;
public ItemSet getUniqueItem() {
ResultSet rs;
Database d=new Database();
ItemSet unique=new ItemSet();
String query="Select id,name from item";
rs=d.sendQuery(query);
try{
while(rs.next()) {
System.out.println(rs.getString(1)+"\t"+rs.getString(2));
Item item=new Item(rs.getString(1),rs.getString(2));
unique.addItems(item);
}
} catch(Exception e) {
System.out.print(e.getMessage());
}
return unique;
}
}
And this is my main class
public class Ap {
public static void main(String args[]) {
Transaction t=new Transaction();
Transaction Ci=new Transaction();
Transaction Li=new Transaction();
ItemSet I=t.getUniqueItem(); //11
}
}
I dont know how to get Items from ItemSet at 11
I tried using
foreach(Item i:I) {
}
But I am getting error.

To be able to use for (Item i : itemSet), your ItemSet class must implement the iterable interface. You could do this by adding the following method to the ItemSet class:
public Iterator<Item> iterator() {
return hold.iterator();
}
Remember that you should add implements Iterable<Item> to the class declaration.
Note that you could always use for (Item i : itemSet.getItemSet()).

In order to use 'foreach' statement, your ItemSet class should implement java.lang.Iterable interface
UPDATE:
See this SO answer about how to implement Iterable interface

The getUniqueItem() method in your Transaction class returns an ItemSet which does not implement the Iterable interface, so you shouldn't expect to be able to iterate over it. You need to get the List<Item> from the ItemSet by calling getItemSet() and iterate over that.
By the way, getItemSet() is probably not a great name for that method, since it returns a List<Item>.

I think your code doesnt make alot of sense and i seriously dont understand why everybody wants to implement the Iterator interface.
First you make use the name Set for a class that contains a List.
Then you recreate a new instance of the List in the addItems() method, which should be addItem() because you want to add individual items to your list.
What you are doing is basically making a list and adding an item to it but the next item you add you recreate the list and you assign the reference of it to the reference of your previous list, thus effectively deleting it.
So you list will never contain more then 1 item.
If you want to have a list as an attribute of a class, then the name of the class you be intuitive, like ItemList for example because that tells you that you have a list of items and that is exactly what it is.
But if it contains only one list then actually its not needed at all because the only thing you do is add a method call in between. You can just use the List interface or any classes that implement it, like ArrayList for example.
I took your code and rewrote it like it would make sense.
I hope it helps you out ;)
public class Transaction {
public ItemList getUniqueItems() {
Database d = new Database();
ItemList unique = new ItemList();
String query="Select id,name from item";
ResultSet rs = d.sendQuery(query);
try {
while(rs.next()) {
System.out.println(rs.getString(1)+"\t"+rs.getString(2));
unique.addItem(new Item(rs.getString(1),rs.getString(2)));
}
}
catch(Exception e){
System.out.print(e.getMessage());
}
return unique;
}
}
public class Ap {
public static void main(String args[]) {
Transaction t = new Transaction();
ItemList i = t.getUniqueItems();
List<Item> list = i.getItemList();
list.get(10); //11 because 0 counts also
}
}
The shorter version would be:
1: the Transation class
public class Transaction {
public List<Item> getUniqueItems() {
Database d = new Database();
List<Item> unique = new ArrayList<Item>();
String query="Select id,name from item";
ResultSet rs = d.sendQuery(query);
try {
while(rs.next()) {
System.out.println(rs.getString(1)+"\t"+rs.getString(2));
unique.add(new Item(rs.getString(1),rs.getString(2)));
}
}
catch(Exception e){
System.out.print(e.getMessage());
}
return unique;
}
}
2: The Ap class:
public class Ap {
public static void main(String args[]) {
Transaction t = new Transaction();
List<Item> list = t.getUniqueItems();
list.get(10); //11 because 0 counts also
// iteration with a foreach loop
for (Item i : list) {
System.out.println(i);
}
// iteration with a for loop
for (int n = 0, s = list.size(); n < s; n++) {
System.out.println(list.get(n));
}
// iteration with a Iterator
Iterator<Item> iterator = list.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
So there is totally no need to implement the Iterator interface anywhere.

Related

Add a boolean attribute, This attribute keeps track if the item was purchased or not

This is my assignment, I'm working on the step 3:
I need to implement a method called getItems() that takes a boolean value and returns a new ArrayList with items having the property that match the given value.
So far When I print it out it just shows the whole list in the array list, not only the objects having true property.
My code:
import java.util.ArrayList;
public class Shoppinglist9_6_pt2 {
ArrayList<Item> shoppingList = new ArrayList<>();
public Shoppinglist9_6_pt2(ArrayList<Item> shoppingList) {
this.shoppingList = shoppingList;
}
public void showList() {
for ( Item item : shoppingList){
System.out.printf("\nItem:%s Ct:%s", item.getName(),
item.getCt());
}
}
public ArrayList<Item> getItems(boolean gotIt) {
gotIt = true;
for (Item item : shoppingList){
if(item.getGotIt() == gotIt){
showList();
}else{
gotIt = false;
}
}
// Todo: return an ArrayList of item that
// match the gotIt true or false value.
// For example if set to True, then return
// an ArrayList of Item with gotIt=True.
return new ArrayList<Item>();
}}
public class Item {
private String name;
private int ct;
private boolean gotIt;
}
public Item(String name, int ct,boolean gotIt) {
this.name = name;
this.ct = ct;
this.gotIt = gotIt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCt() {
return ct;
}
public void setCt(int ct) {
this.ct = ct;
}
public boolean getGotIt(){
return gotIt;
}
public void setGotIt(boolean gotIt) {
this.gotIt = gotIt;
}
#Override
public String toString() {
return "Item :" +
"name='" + name + '\'' +
", ct=" + ct +
"Got it=" + gotIt;
}
}
This is my main:
public class inClass_Shopping_9_6_pt2 {
public static void main(String[] args) {
Shoppinglist9_6_pt2 sl = new Shoppinglist9_6_pt2();
sl.addItem( "Banana", 6,true);
sl.addItem("Coconut", 2,false);
sl.addItem("Apple", 12,true);
sl.getItems(true);
}
}
Also, you might observe the method gotIt() is grayed out & says parameters can be converted to a local varaible, same with the return. 'Item' in ArrayList<Items> is grayed out and says explicit type argument item can be replaced with <>, but this is the template my professor had sent us, and we need to follow it.
You have the new instance variable, you have the getters and setters, just the getItems method does not yet do the job...
You want to get a list with all the entries of the shopping list that have the attribute gotIt either true or false depending on the gotIt variable. How can you use the gotIt variable to get all the items you want?
Normally one would choose different names for the parameter of getItems, so it doesn't collide with the attributes name
You need to perform the following steps:
create a new ArrayList.
iterate through the sopping list and add each item with gotIt property matches the provided boolean value into the newly created ArrayList.
return the list.
That's how it might look like:
public ArrayList<Item> getItems(boolean gotIt) {
ArrayList<Item> items = new ArrayList<>();
for (Item item : shoppingList) {
if (item.getGotIt() == gotIt) {
items.add(item);
}
}
return items;
}
Note: although according to the assignment requirements you have to use ArrayList as a type in your code, it's not good practice to make the code dependent on concrete implementations. See What does it mean to "program to an interface"?
I know I have join party late, and my answer is not different from Alexandar.
I'm not offering a lot of assistance, still you can try using lambdas.
For instance
public ArrayList<Item> getItems(boolean gotIt) {
ArrayList<Item> items = new ArrayList<>();
shoppingList.forEach(item -> {
if(item.getGotIt() == gotIt) items.add(item);
});
return items;
}
For print,
sl.getItems(false).forEach(System.out::println);

Access List item without waiting for the List to be populated fully

I have a List as per following:
private void someMethod () {
String str= "someStrParam";
private int theCount = 0;
List<String> itemList = getListMethod(str);
if (theCount < itemList.size()) {
return itemList.get(theCount++);
} else {
return null;
}
}
Question: As soon as a List item is added to the List in the getListMethod, how can I access it immediately in the someMethod without waiting for the next item to be added? Or is there way a way we put a monitor on getListMethod so that, as soon as the an item is added there, we can query the itemList ?
You can use the PropertyChangeSupport with your custom list:
class MyList<T> {
private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
private final List<T> itemList = new ArrayList<>();
public void addName(T name) {
itemList.add(name);
propertyChangeSupport.firePropertyChange("item", null, Collections.unmodifiableList(itemList));
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
}
Usage:
public static void main(String[] args) {
MyList<String> myBean = new MyList<>();
myBean.addPropertyChangeListener(evt -> System.out.println("Hello"));
myBean.addName("Hello");
}
To simplify, to test the usage and to understand answer given by #PavlMits, I tried like this:
public class MyListUsage {
public static void main(String[] args) {
MyList<String> myList = new MyList<>();
myList.addPropertyChangeListener(evt -> callThisOnAddItemToList ());
myList.addName("foo");
myList.addName("bar");
myList.addName("blah-blah");
}
private static void callThisOnAddItemToList () {
System.out.println("Do something here as and when an item added to list ......");
}
}
And I got the below output:
Do something here as and when an item added to list ......
Do something here as and when an item added to list ......
Do something here as and when an item added to list ......

A point of sale application using ArrayList of Item class. How to return isolated/specific values from the list?

Java noob here. I am trying to build a simple point of sale checkout application. I have a simple item database in mysql shown in the pic below.
I have an Item class built as below with getters and setters for each column
public class Item {
private String itemName;
private double unitPrice;
private boolean weightReqd;
private boolean quanReqd;
private boolean recalled;
private boolean ageRest;
private boolean eCpn;
private double eCpnAmt;
public Item(){}
public Item(String itemName, double unitPrice, boolean weightReqd, boolean quanReqd, boolean recalled,
boolean ageRest, boolean eCpn, double eCpnAmt){
this.itemName = itemName;
this.unitPrice = unitPrice;
this.weightReqd = weightReqd;
this.quanReqd = quanReqd;
this.recalled = recalled;
this.ageRest = ageRest;
this.eCpn = eCpn;
this.eCpnAmt = eCpnAmt;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public boolean isWeightReqd() {
return weightReqd;
}
public void setWeightReqd(boolean weightReqd) {
this.weightReqd = weightReqd;
}
public boolean isQuanReqd() {
return quanReqd;
}
public void setQuanReqd(boolean quanReqd) {
this.quanReqd = quanReqd;
}
public boolean isRecalled() {
return recalled;
}
public void setRecalled(boolean recalled) {
this.recalled = recalled;
}
public boolean isAgeRest() {
return ageRest;
}
public void setAgeRest(boolean ageRest) {
this.ageRest = ageRest;
}
public boolean iseCpn() {
return eCpn;
}
public void seteCpn(boolean eCpn) {
this.eCpn = eCpn;
}
public double geteCpnAmt() {
return eCpnAmt;
}
public void seteCpnAmt(double eCpnAmt) {
this.eCpnAmt = eCpnAmt;
}
}
And then i am using setters from the Item class to add the records to a List of Items (List).
public class CreateItemList {
private static Connection conn = null;
public List<Item> itemList = new ArrayList<Item>();
public void createDbConnection() throws ClassNotFoundException, SQLException {
String myUrl = "jdbc:mysql://localhost:3306/itemdb?autoReconnect=true&useSSL=false";
conn = DriverManager.getConnection(myUrl, "******", "*********");
}
public void addItemsToList() throws SQLException, ClassNotFoundException {
String query = "SELECT * FROM item_source";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
try
{
while (rs.next())
{
Item item = new Item();
item.setItemName(rs.getString("Item Name"));
item.setUnitPrice(rs.getDouble("Unit Price"));
item.setWeightReqd(rs.getBoolean("Weight Reqd"));
item.setQuanReqd(rs.getBoolean("Quan Reqd"));
item.setRecalled(rs.getBoolean("Recall"));
item.setAgeRest(rs.getBoolean("Age Rest"));
item.seteCpn(rs.getBoolean("Ecpn"));
item.seteCpnAmt(rs.getDouble("Ecpn Amt"));
itemList.add(item);
}
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e);
}
st.close();
}
}
Now the next thing i want to do is create exception handler methods. So if the user enters an item that is flagged as "true" for weight required, i want the is WeightReqd method to return true. But I'm struggling on this. I'm not sure how to return the boolean value for the item scanned, specifically for the Weight Reqd field.
public class ExceptionsHandler {
public boolean isWeightReqd(List<Item> itemList){
//HOW DO I RETURN THE BOOLEAN VALUE FOR THE WEIGHT REQD FIELD FROM THE LIST??
return false;
}
Would really appreciate the help! Can also take instructions on the general structure of this program, if there are better ways to do it!
You need to call your ExceptionHandler class for a specific item scanned. You dont need to pass the whole list in your isWeightReqd() method. Only pass your Item. Change your method signature to: public boolean isWeightReqd(Item itemList) and should get it.
I think this is a case where a hashmap might make more sense than an arraylist, using the name of the item as a key. Regardless once you have found that item all you need to call is
boolean b = item.isWeightReqd();
As per my understanding from your inputs in the comments, the user will enter the Item Name of an item and you want to return whether weight is required or not. So, the method signature would have the list of items from the DB and the item name entered by the user.
Option 1:
You can stream the contents of the list, find the item whose itemName matches the one entered by the user and return its weightReqd.
public boolean isWeightReqd(List<Item> itemList, String itemScanned) {
return itemList.stream()
.filter(item -> item.getItemName().equals(itemScanned))
.findFirst()
.map(Item::isWeightReqd)
.orElseThrow(() -> new RuntimeException("The item " + itemScanned
+ " does not exist"));
}
However, the worst-case running time for this is O(n) if the item scanned is not present or if it is the last one in the list.
Option 2:
If you want an O(1) lookup, you can convert the List<Item> after fetching it from the DB as a Map whose key is the itemName and value is the Item itself.
Map<String, Item> items = itemList.stream()
.collect(Collectors.toMap(Item::getItemName, Function.identity()));
public boolean isWeightReqd(List<Item> itemList, String itemScanned) {
if (items.containsKey(itemScanned)) {
return items.get(itemScanned).isWeightReqd();
}
throw new RuntimeException("The item " + itemScanned + " does not exist");
}
//Or by using Optional
Optional.ofNullable(items.get(itemScanned))
.map(Item::isWeightReqd)
.orElseThrow(() -> new RuntimeException("The item " + itemScanned
+ " does not exist"));

Infinite loop because the iterator doesn't move

There is a some class which implementing an interface Selector. I should use iterator() in its methods.
private class SequenceSelector implements Selector {
private T obj = items.iterator().next();
public boolean end() { return !items.iterator().hasNext(); }
public T current() { return obj; }
public void next() { obj = items.iterator().next(); }
}
items is a ArrayList. obj is a value in order to save the first sequence member before the first next() using.
With a following code the program goes into an infinite loop in which is printed only the first member of sequence.
while(!selector.end()) {
System.out.print(selector.current() + " ");
selector.next();
}
Why does this happens? Though I use next() method, the iterator doesn't move.
Every time you call items.iterator() you create a new iterator.
Create one iterator at the start, and use that repeatedly.
private class SequenceSelector implements Selector {
private final Iterator<T> iterator = items.iterator();
private T obj = iterator.next();
public boolean end() { return !iterator.hasNext(); }
public T current() { return obj; }
public void next() { obj = iterator.next(); }
}

stuck on a java setter method

I have a StockList class which contains a linkedlist and can control stock using a variety of method. However i am stuck on what to put inside my method body for my updateItemPrice method.
Do I need to use a setter to set the new item price, if so how would i go about that?
This is my code so far, any help would be much appreciated!
import java.util.*;
public class StockList {
{
private LinkedList<StockItem> stock
= new LinkedList<StockItem>();
public StockList() {};
// Adds item to end of stock list
public void addItem(StockItem item)
{
this.stock.addLast(item);
}
// Removes item identified by productID from stock list
public void deleteItem(String itemID)
{
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
stock.remove(itr.previousIndex());
break;
}
}
}
// Updates price of existing item
public void updateItemPrice(String itemID, double price)
{
???
}
// Updates quantity of existing item
public void updateItemQuantity(String itemID, int quantity)
{…}
// Updates re-order level of existing item
public void updateReOrderLevel(String itemID,
int reOrderLevel)
{…}
// Returns formatted representation of the stock list
public String formatStockList()
{…}
// Returns formatted representation of re-order list
// Items are on this list if quantity < reOrderLevel
public String formatReOrderList()
{…}
}
}
StockItem need to have the setter method to set Price like setPrice
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
item.setPrice(price);
break;
}
}
How ever there is also problem in your delete code...
public void deleteItem(String itemID)
{
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
stock.remove(itr.previousIndex());
break;
}
}
}
This will give you concerrent Access exception. use below code instead.
public void deleteItem(String itemID)
{
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
itr.remove(); // Removes last obejct returned by itr.next()
break;
}
}
}
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
item.setPrice(price);
break;
}
}
Nevertheless, it may be a better idea to use an HashMap<String, StockItem>() to store the ids of the stock objects and update the price would be more easy for you.
And you should store ids as Long instead of String, so this would be an HashMap<Long, StockItem>()
Since you have an itemId, I would not use a List. I would use a Map, with itemId as the key and the StockItem as the value. Then your add and delete methods become much simpler
Map<String, StockItem> stocks = new HashMap<String, StockItem>();
public void addStockItem(StockItem stockItem) {
this.stocks.put(stockItem.getItemId(), stockItem);
}
public void deleteStockItem(StockItem stockItem) {
this.stocks.remove(stockItem.getItemId());
}
then updating becomes as simple as getting the appropriate item out of the map and updating its price.
public void updateStockItem(String id, Double price) {
StockItem item = this.stocks.get(id);
item.setPrice(price);
}
// Updates price of existing item
public void updateItemPrice(String itemID, double price)
{
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
item.setPrice(price);
break;
}
}
}
Everybody's answer here except #hvgotcodes has a very basic bug:
if(item.getitemID() == itemID) // this won't work!
#hvgotcodes solution is the correct way of implementing your class. Using a HashMap is far better than iterating over LinkedList to delete stuff.

Categories