How to add items to arraylist and modify a feature - java

I am trying to add items to my array list with an action listener on a pop up window. You can see the action listener here. The problem that I am now having is I do not know how to add the inputs to my array list. Part of this problem is that I need to set my item number to 1 higher than the highest in my list. My array list is named as such:
private static ArrayList<InventoryItem> inventory = new ArrayList<>();
and the class for InventoryItem looks like this:
public class InventoryItem { //Delcare variables below
DecimalFormat formatted = new DecimalFormat("#,###.00");//set up decimal format for displaying 12.34 type values
String itemName;
int itemNumber;
public String getItemName() {
return itemName;
}
public int getItemNumber(){
return itemNumber;
}
int inStock;
double unitPrice;
double value;
double restockingFee;
double inventoryValue;
public InventoryItem(String itemName, int itemNumber, int inStock, double unitPrice) { //declare variables for this class
this.itemName = itemName;
this.itemNumber = itemNumber;
this.inStock = inStock;
this.unitPrice = unitPrice;
stockValue(); //call stock value
}
}
So my question is two parts. The first is how do I get my itemNumber to increment to 1 higher than the highest? Do I simply do a bubble sort to find the highest? And the second part is how do I get it to add all items, including this incremented itemNumber, into my original arraylist?
Note
If needed I can paste my code in it's entirety on pastebin as it is somewhat large.
EDIT: Per #Prabhakaran I have added some code and I am almost there. I have almost gotten this to work, however when I start to look through my list I do not see the added feature so how can I be sure that I am actually adding it?
String newItemName = String.valueOf(xField);
String text1 = yField.getText();
String newInventoryAmount = String.valueOf(text1);
int newNumber = Integer.parseInt(newInventoryAmount);
String text2 = zField.getText();
String newUnitPrice = String.valueOf(text2);
double newPrice = Double.parseDouble(newUnitPrice);
for (int i = 0; i >= inventory.size(); i++) {
inventory.get(inventory.size() ).getItemNumber();
int newItemNumber;
newItemNumber = i + 1;
InventoryItem item = new InventoryItem(newItemName, newItemNumber, newNumber, newPrice);
inventory.add(item);
What am I missing here? Shouldn't this simply add an item to my arraylist? I know it must be something really easy, I just can't seem to figure it out.
Here is my sort by ItemName:
static ArrayList sortInventory(ArrayList<InventoryItem> unsorted) {
ArrayList<InventoryItem> sorted = new ArrayList<>(); //create new array list to sort
InventoryItem alpha = null;
int lowestIndex = **-1**;
while (unsorted.size() > 0) { //while my unsorted array is less than 0 do the following
for (int i = 0; i < unsorted.size(); i++) { //increment through
if (alpha == null) {
alpha = unsorted.get(i); //get the next line in the inventoryItem array
lowestIndex = i;
} else if (unsorted.get(i).itemName.compareToIgnoreCase(alpha.itemName) < 0) { //compare items to determine which has a higher value
alpha = unsorted.get(i);
lowestIndex = i;
}
}
sorted.add(alpha); //reset the index so it will loop until there are no more items in the unsorted array
unsorted.remove(lowestIndex);
alpha = null;
lowestIndex = **0**;
}
return sorted; //return the sorted arraylist
}
EDIT: Corrected the lowestIndex and it goes good as gold.

Do like this
private static ArrayList<InventoryItem> inventory = new ArrayList<>();
String newItemName = String.valueOf(xField);
String newInventoryNumber = String.valueOf(yField);
int newNumber = Integer.parseInt(newInventoryNumber);
String newUnitPrice = String.valueOf(zField);
double newPrice = Double.parseDouble(newUnitPrice);
InventoryItem item =new InventoryItem(newItemName , newInventoryNumber , newNumber , newUnitPrice ) ;
inventory.add(item);
update
class SimpleComparator implements Comparator<InventoryItem> {
#Override
public int compare(InventoryItem o1, InventoryItem o2) {
return new Integer(o1.getItemNumber()).compareTo(o2.getItemNumber());
}
}
//Sorting based on the itemNumber.
Collections.sort(inventory,new SimpleComparator());
int newItemNumber = inventory.get(inventory.size() - 1).getItemNumber();
newItemNumber ++;

You could create your own ArrayList with Observer support:
public class InventoryItemArrayList extends ArrayList {
private static final long serialVersionUID = 4550719458611714650L;
private List listeners = new ArrayList();
public void addInventoryItemAddedListener(InventoryItemAddedListener listener) {
this.listeners.add(listener);
}
#Override
public boolean add(InventoryItem e) {
boolean add = super.add(e);
fireInventoryItemAdded(e);
return add;
}
private void fireInventoryItemAdded(InventoryItem e) {
for (InventoryItemAddedListener element : listeners) {
element.inventoryItemAdd(e);
}
}
#Override
public void add(int index, InventoryItem element) {
super.add(index, element);
fireInventoryItemAdded(element);
}
#Override
public boolean addAll(Collection c) {
boolean addAll = super.addAll(c);
fireInventoryItemAdded(c);
return addAll;
}
private void fireInventoryItemAdded(Collection c) {
for (InventoryItem inventoryItem : c) {
fireInventoryItemAdded(inventoryItem);
}
}
#Override
public boolean addAll(int index, Collection c) {
boolean addAll = super.addAll(index, c);
fireInventoryItemAdded(c);
return addAll;
}
}

Related

Java: Using the index of a linkedList, how to change item for desired value

I want to only change the int value of a specific item in a LinkedList, to a new int value. I would also like to understand the logic of how it is done, not only the code.
p.s I can not change anything, I can only add to the inside of the methods.
Thank you.
For example:
[Green tea, 1] to [Green tea, 2]
The method where this needs to happen
public void changeItemCount(int k, int m){
}
Class where the question is
import java.util.LinkedList;
import java.util.ListIterator;
public class GroceryList {
//this class will create an object that contains a list of Grocery Items
//variable
private LinkedList<GroceryItem> glist; //holds GroceryItems
//constructor: instantiates glist to an empty groceryList
public GroceryList() {
glist = new LinkedList<GroceryItem>();
}
// return number of GroceryItems in glist
public int getSize() {
return glist.size();
}
//return GroceryItem at requested index
public GroceryItem getItem(int k) {
GroceryItem m = glist.get(k);
return m;
}
//add GroceryItem x to end of glist
public void addItem(GroceryItem x) {
glist.add(x);
}
//Remove item at index k from glist
public GroceryItem removeItem(int k ) {
return glist.remove(k);
}
//change item count for k item in glist to m
public void changeItemCount(int k, int m) {
//need help here
}
//Should work as is
public void sortList( ) {
glist.sort(null);
System.out.println("Sorted GroceryList: " + glist);
}
}
other class in relation:
public class GroceryItem implements Comparable<GroceryItem> {
//this class will create items from a Grocery Store and the desired quantity
//variables
private String name; //grocery item name
private int count; // number needed; make sure count is always >= 0
//set count = 1; set name = s in following constructor
//if only a string is passed, default count is set to 1
public GroceryItem ( String s) {
count = 1;
name = s;
}
//constructor
// set name = s and set count = initCount in following constructor
//if a string and an int are passed then we set them to the passed values
public GroceryItem ( String s , int initCount) {
name = s;
count = initCount;
}
//returns the current count
public int getCount() {
return count;
}
//returns a fixed/known amount
public void setCount(int m) {
count = m;
}
public String getName() {
return name;
}
//#Override
public int compareTo(GroceryItem o) {
if( name.compareTo(o.getName() ) < 0) //less than compared item
return -1;
else if (name.compareTo(o.getName()) > 0) //greater than compared item
return 1;
else
return( count - o.count); //duplicated item?
}
//toString method: formatting: [bananas, 3]
public String toString() {
name.toString();
String temp = Integer.toString(count);
String formatt = name + ", " + temp ;
return formatt;
}
}
main driver:
public class GroceryListDriver {
//this class tests the methods of the two other classes
public static void main(String[] args) {
// TODO Auto-generated method stub
//creating 10 items in GroceryItem
GroceryItem items1 = new GroceryItem("banana", 5);
GroceryItem items2 = new GroceryItem("apples", 5);
GroceryItem items3 = new GroceryItem("pea soup", 2);
GroceryItem items4 = new GroceryItem("apples", 3);
GroceryItem items5 = new GroceryItem("wheat bread", 2);
GroceryItem items6 = new GroceryItem("tuna fish", 5);
GroceryItem items7 = new GroceryItem("potatoes", 4);
GroceryItem items8 = new GroceryItem("sourdough bread", 1);
GroceryItem items9 = new GroceryItem("chedadar cheese", 1);
GroceryItem items10 = new GroceryItem("green tea", 1);
//creating groceryList called groceryList
GroceryList groceryList = new GroceryList();
//adding to the list
groceryList.addItem(items1);
groceryList.addItem(items2);
groceryList.addItem(items3);
groceryList.addItem(items4);
groceryList.addItem(items5);
groceryList.addItem(items6);
groceryList.addItem(items7);
groceryList.addItem(items8);
groceryList.addItem(items9);
groceryList.addItem(items10);
//print current list
//groceryList.printGroceryList(null);
//sorting groceryList
//groceryList.sortList();
//change count of green tea to 2
System.out.println(groceryList.getItem(9));
}
}
Try this one:
public void changeItemCount(int k, int m){
GroceryItem item = getItem(k); //just get the item from list
item.setCount(m); //and change the count value
}

How to join a String array to a int array and sort by number (higher to lower) in Android?

I have two arrays:
int[] sinais = new int[arraySinais.length];
String[] arraySSID = new String[] { };
And I joined them into one array:
String[] arrayScan = new String[arraySinais.length];
for (int i = 0; i < arraySSID.length; i++) {
arrayScan[i] = arraySSID[i] + " " + sinais[i];
}
But now I need to sort this new array by numbers in a decreasing order and put an Image inside ListView depending the numbers, and I do not have any idea how to do this.
you can use create your own object which contains the int and the string and use arraylist to sort
First create your own custom Element (Object) which mainly consist of an int number and a String string.
public class Element implements Comparable<Element>{
private int number;
private String string;
public Element(String string, int number) {
this.number =number;
this.string = string;
}
//create custom constructors if its allowed to define an element without a number or string
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
#Override
public int compareTo(Element e) {
return number - e.number;
}
}
Implement comparable as above to sort depending on the number value, but keep in my mind that your element won't sort stand alone strings.
If you want to sort your list depending on strings if a number doesn't exist use this implementation of comparTo() method:
#Override
public int compareTo(Element e) {
if(e.number != 0) return number - e.number;
return string.compareTo(e.string);
}
While using implement a List of elements and use Collections sort() method and you are good to go:
List<Element> list = new ArrayList<>();
//add Elements
Collections.sort(list);
I used the method below, by Bubble Sort, and solve my problem:
> for (int i = Sinais.length; i >= 1; i--){
> for (int j = 1; j < i; j++){
> if (Sinais[j-1]<Sinais[j]){
> int aux = Sinais[j];
> String aux2 = ArraySSID[j];
> Sinais[j] = Sinais[j-1];
> ArraySSID[j] = ArraySSID[j-1];
> Sinais[j-1] = aux;
> ArraySSID[j-1] = aux2;
> }
> }
> }

How to find the second largest element in an array of objects

I need to know the way to find the second largest element among an array of objects. for eg.
if there is an array of objects of a Book class with attributes like book name, price, in stock quantity
Book[] b=new Book[];
b[0]=new Book("x",200,50);
b[1]=new Book("y",100,44);
b[2]=new Book("z",500,29);
How can we list the book with second largest price along with other attributes like name and in stock quantity
Make a List of Books from it, sort it using Collections.sort and take the element on index 1.
List<Book> booklist = new ArrayList<Book>(Arrays.asList(b));
Collections.sort(booklist, new Comparator<Book>() {
#Override
public int compare(Book o1, Book o2) {
return o2.getPrice() - o1.getPrice();
}
});
if (booklist.size() > 1) {
System.out.println(booklist.get(1));
}
You can loop through this Array to find the largest and with this the second largest Element of the Array. Because the Elements are Objects you have to get the Value that you want to compare from the element with a getter or the variable is public in the objects.
public int getSecondLargest(Object[] obj){
int length = obj.length;
int largest = 0;
int secondLargest = 0;
for(int i = 0; i<length; i++){
if(obj[largest].getValue() <= obj[i].getValue()){
secondLargest = largest;
largst = i;
}
}
return secondLargest;
}
I think you should implements Interface Comparable.
and then use Collections.sort();
Implements a Comparator And sort your array, then pick second element.
class BookPriceComparator implements Comparator<Book> {
#Override
public int compare(Book a, Book b) {
return a.getPrice() - b.getPrice();
}
}
Arrays.sort(bookArr, new BookPriceComparator ());
import java.util.*;
//here you can make changes or you can create your own new class
//to sort book according to pages
class sortPrice implements Comparator<Test> {
public int compare(Test i1, Test i2) {
Integer x = i1.getPrice(), y = i2.getPrice();
return y.compareTo(x); // <--- changed
}
}
// in your case Test class could be Book class
public class Test {
/**
* #param args
*/
int price , page ;
String name;
Test(String n , int p ,int pg){
name=n;
price=p;
page=pg;
}
public String toString(){
return name+" "+price +" "+page ;
}
public String getName(){
return name;
}
public int getPage(){
return page;
}
public int getPrice(){
return price;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test[] b=new Test[3];
b[0]=new Test("x",200,50);
b[1]=new Test("y",100,44);
b[2]=new Test("z",500,29);
ArrayList<Test> a = new ArrayList<>();
for(int i=0;i<3;i++){
a.add(b[i]);
}
sortPrice s= new sortPrice(); // required to pass as argument to tell
//based on which sorting order you want to sort
Collections.sort(a,s ); //here we are sorting Test(Book) based on price.
System.out.println(a.get(1)); // printing arrayList //<----- changed
}
}

Reading input from a text file using scanner into array

I am trying to read the input from a text file using scanner class and pass into an array. I know how to read the input using scanner class. The only problem I am facing here is I am unable to pass into the array.
public class ReadItemData {
public static void main(String[] args) throws Exception {
Scanner aScanner = new Scanner(new FileReader(
"src//chapter11//Items.txt"));
while (aScanner.hasNext()) {
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
System.out.println(code + " " + sku + " " + qty);
}
}
The above code works without the array concept. I want to extend the same concept to read the above data into a array of size 100. Any suggestions would be helpful. My final aim is to sort the input which is in array by code,sku
This is how I used comparable interface for sorting. How can I extend this concept for arrays?
I used something like this for sorting(without the array concept)
class Item implements Comparable {
private int qty;
private String sku,code;
public Item(int qty, String sku,String code) {
this.qty = qty;
this.sku = sku;
this.code = code;
}
public int getQty() {
return qty;
}
public String getSku() {
return sku;
}
public String getCode() {
return code;
}
public int compareTo(Object o) {
Item i = (Item) o;
if (this.getQty() < i.getQty())
{
return -1;
}
if (this.getQty() > i.getQty())
{
return 1;
}
return 0;
}
}
Thanks!!
String[] array = new String[100];
int currentIndex = 0;
while (aScanner.hasNext()) {
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
array[currentIndex] = code;
array[currentIndex++] = sku;
array[currentIndex++] = ""+qty;
currentIndex++;
}
As mentioned in the comments, you can use 2D array of 100 rows and 3 columns like this:
Object[][] array = new Object[100][3];
int i=0,j=0;
while (aScanner.hasNext()) {
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
array[i][j++] = code; // array of row i and columns j
array[i][j++] = sku;
array[i][j] = qty;
i++; // increment i since it's for rows
j=0;//reset j because it's for columns
}

Array concept on trying to get the no of lines in the file

I have below code which reads the input from a file using scanner class and sorts the input using comparable interface. This code works fine for a fixed array size but I want to count the no.of lines which are there in the file.
public class ReadItemData {
public static void main(String[] args) throws Exception {
Scanner aScanner = new Scanner(new FileReader(
"src//chapter11//Items.txt"));
double avg = 0;
double sum = 0;
Item[] itemArray = new Item[5];
while (aScanner.hasNext())
{
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
itemArray[count] = new Item(code, sku, qty);
System.out.println(itemArray[i]);
i++;
}
Arrays.sort(itemArray[i]);
System.out.println();
for (Item it : itemArray)
{
System.out.println(it);
sum += qty;
}
avg = sum / 5;
if(qty <= (avg - 10))
{
System.out.println("Quantity is 10 less than the average quantity");
}
}
}
class Item implements Comparable {
private int qty;
private String sku,code;
public Item(String code, String sku,int qty) {
this.code = code;
this.sku = sku;
this.qty = qty;
}
public String getCode() {
return code;
}
public String getSku() {
return sku;
}
public int getQty() {
return qty;
}
public int compareTo(Object o) {
Item i = (Item) o;
return (this.sku).compareTo(i.sku);
}
}
I tried declaring a int variable count and passed it to the array but I am getting ArrayIndexOutOfBoundsException
int count = 0;
Item[] itemArray = new Item[count];
One more issue I am facing is I am calculating the sum inside the loop,but I am not getting the desired results
My input file
PAP ENT 82
WAR HOT 79
TIM JUT 92
BON BLA 76
BON MAG 45
The sum of the quantity goes to 374,but in my code it's calculated to 225 and I am unable to figure out where I am doing wrong.
Any help is appreciated.
Thanks!!
Instead of adding these into a fixed array add them into a java list. Once you have filled the list up use listClass.size() to retrieve the size of the list.
Here's some implementation:
List<Item> itemList = new List<Item>();
while (aScanner.hasNext())
{
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
itemList.add(new Item(code, sku, qty));
System.out.println(itemList.get(i));
i++;
}
Now use itemList.size() anywhere to retrieve how many entries. You are implementing arrays wrong btw. When you are getting the array out of bounds error is due to the fact that you are initializing the array with 0 positions.
Your sum is incorrect due to not getting the correct item value:
for (Item it : itemArray)
{
System.out.println(it);
//You must get the iterated item quantity (I assume you don't have setters and
//getters
sum += it.qty;
}

Categories