Remove/change specific object from an ArrayList - java

I'm building a simplified inventory program for a "hardware store" in Java. I want to register the items by name and quantity into an array, and also remove or change the quantity if the item gets sold.
i believe i'm done with 80 percent of the work. I just can't figure out how to remove or change the object after storing it. Has this something to do with the equals(Object obj) method? I'm finding it hard to understand how to use the method in my case.
Class for the hardware items:
public class Items {
private String item;
private String quantity;
public Items(){
}
public String getName() {
return item;
}
public String getType() {
return item;
}
public String getQuantity() {
return quantity;
}
public void setItem(String item) {
this.item=item;
}
public void setQuantity(String quantity) {
this.quantity=quantity;
}
}
--
public class Hardware {
public static void main(String[] args) {
List<Items> allItems =new ArrayList<Items>();
Scanner input = new Scanner(System.in);
int choice;
while(true){
System.out.println("Inventory\n");
System.out.print("1.) Add new items to your inventory. \n");
System.out.print("2.) Delete items from your inventory.\n");
System.out.print("3.) Change quantity of an item.\n");
System.out.print("6.) Exit\n");
System.out.print("\nEnter Your Menu Choice: ");
choice = input.nextInt();
Scanner in = new Scanner(System.in);
switch(choice){
case 1:
Items myItems = new Items();
System.out.println("Item:");
myItems.setItem(in.nextLine());
System.out.println("Quantity?");
myItems.setQuantity(in.nextLine());
allItems.add(myItems);
System.out.println(allItems);
System.out.println("The inventory contains the following items:");
for(int i = 0; i < allItems.size(); i++) {
System.out.println(allItems.get(i).getName());
}
break;
case 6:
System.out.println("Exiting Program...");
System.exit(0);
break;
default :
System.out.println("This is not a valid Menu Option! Please Select Another");
break;
}
}
}
}

You should implement the equals method in the Items class like this:
public boolean equals(Object object){
if(this == object){
return true;
}
if(object instanceof Items){
Items newItem = (Item) object;
return item.equals(newItem.item) && quantity.equals(newItem.quantity);
}
return false;
}
Then for the removing and changing options, create an Item object with the user inputs, and loop over through the List, compare each Item object with the one created with the user inputs, until you find the desired object, and then perform the necessary action.

Related

Set up while statement to print out methods?

Not the best title but basically I want to ask the user to enter a temperature, and then displays a list of substances that will freeze at that temperature and those that boil at that temperature. I want it to be in a while loop and I want the user to be able to go until they want to stop. Heres what I have so far, my first class and then a tester
public class FreezingPoint {
private int temperature;
public double getTemperature() {
return temperature;
}
public void setTemperature() {
this.temperature = temperature;
}
public boolean isEthylFreezing() {
boolean status;
if (temperature <= -173.0)
status = true;
else
status = false;
return status;
}
public boolean isEthylBoiling() {
boolean status;
if (temperature >= 172.0)
status = true;
else
status = false;
return status;
}
public boolean isOxygenFreezing() {
boolean status;
if (temperature <= -362.0)
status = true;
else
status = false;
return status;
}
public boolean isOxygenBoiling() {
boolean status;
if (temperature >= -306.0)
status = true;
else
status = false;
return status;
}
public boolean isWaterFreezing() {
boolean status;
if (temperature <= 32)
status = true;
else
status = false;
return status;
}
public boolean isWaterBoiling() {
boolean status;
if (temperature >= 212)
status = true;
else
status = false;
return status;
}
}
and now tester class
import java.util.Scanner;
public class TestFreezingPoint {
public static void main(String[] args) {
FreezingPoint fp = new FreezingPoint();
double temperature;
Scanner sc = new Scanner(System.in);
System.out.println("please enter a temp");
temperature = sc.nextDouble();
System.out.println("Is Water Freezing?" + fp.isWaterFreezing());
}
}
My problem is that the code isn't working properly and I'm confused as to where to go from here. I know how to setup the while loop and how to make it go until I want to stop but I'm not sure on how to properly print out the list of substances that will be displayed based off the users inputted temperature
Any help appreciated, pretty new to java and been stuck on this awhile
Thanks
I think you should use a different way of testing if something boils or freezes at a given temperature. In your example you would have to add two methods for every substance and then find a way to cycle through them.
It would probably be a lot easier if you used for example a list and then use a switch() statement to only add the substances to the list that boil or freeze at the given temperature. If you make a method that does so and give it the temperature as a parameter and have it return the populated list, you could easily loop through the list and print out every element.
I made a quick example for you:
public List<String> getSubstances(int temperature){
List<String> substances = new ArrayList<String>();
switch(temperature){
case 0:
substances.add("Water");
case 100:
substances.add("Water");
}
return substances;
}
This would be a way easier solution and you can cycle through the list very easily to print it out.
I would suggest to use a class to represent the substances:
public class Substance {
private String name;
private double tempFreeze;
private double tempBoil;
public Substance(String name, double tempFreeze, double tempBoil) {
this.name = name;
this.tempFreeze = tempFreeze;
this.tempBoil = tempBoil;
}
public double getTempBoil() { return tempBoil; }
public double getTempFreeze() { return tempFreeze; }
public String getName() { return name; }
public String getState(double temp) {
if (temp <= tempFreeze) {
return "freeze";
} else if (temp >= tempBoil) {
return "boil";
}
return "liquid";
}
}
To be used like :
public static void main(String[] args) {
List<Substance> list = new ArrayList<>();
list.add(new Substance("ethyl", -173, 172));
list.add(new Substance("Oxygen", -362, -306));
list.add(new Substance("water", 32, 212));
Scanner sc = new Scanner(System.in);
do {
System.out.println("please enter a temp");
double temperature = sc.nextDouble();
sc.nextLine(); //consume return char
for (Substance s : list) {
System.out.println(s.getName() + " is in state : " + s.getState(temperature));
}
System.out.println("\nDo you want to stop ? Write 'yes' to stop");
} while (!sc.nextLine().contains("y"));
}
Execution example :
please enter a temp
125
ethyl is in state : liquid
Oxygen is in state : boil
water is in state : liquid
Do you want to stop ? Write 'yes' to stop
y

Java Queue, Dequeue and Printing All Values Within The Queued/Dequeued List

Hello I think I'm really having a hard time with this part. I'm making a program that accepts a value from the user a first name and last name, and then Queues it (CASE1). Then is able to dequeue it (CASE2) and finally show everything on the list. There are no errors on the IDE, but I cant get the result that I want, At CASE 2 it throws the exception error, means that the list that gets passed to it is empty. At CASE 3 no values are shown. How do I fix this?
import java.util.*;
import java.util.Iterator;
class Customer2 {
public String lastName;
public String firstName;
public Customer2() {
}
public Customer2(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}
class HourlyCustomer2 extends Customer2 {
public double hourlyRate;
public HourlyCustomer2(String last, String first) {
super(last, first);
}
}
class Queue1<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
// return a Customer2 with null values if empty? (up to you)
return list.remove(0);
}
public E isNotEnd(){
return list.getLast();
}
public boolean hasItems() {
return !list.isEmpty();
}
public boolean isEmpty() {
return list.isEmpty();
}
public Iterator<E> iterator() {
return list.iterator();
}
public E removeFirst() {
return list.removeFirst();
}
public E getFirst() {
return list.getFirst();
}
public int size() {
return list.size();
}
public boolean hasNext() {
return false;
}
public void addItems(Queue1<? extends E> q) {
while (q.hasNext()) list.addLast(q.dequeue());
}
}
public class something {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input1;
String input2;
int choice = 1000;
Queue1<Customer2> empList;
empList = new Queue1<Customer2>();
Queue1<HourlyCustomer2> hList;
hList = new Queue1<HourlyCustomer2>();
do {
System.out.println("================");
System.out.println("Queue Operations Menu");
System.out.println("================");
System.out.println("1,Enquene");
System.out.println("2,Dequeue");
System.out.println("3,View queue");
System.out.println("0, Quit\n");
System.out.println("Enter Choice:");
try {
choice = sc.nextInt();
switch(choice) {
case 1:
System.out.println("\nPlease enter last name: ");
input1 = sc.next();
System.out.println("\nPlease enter first name: ");
input2 = sc.next();
hList.enqueue(new HourlyCustomer2(input1, input2));
empList.addItems(hList);
System.out.println("\n"+(input2 + " " + input1) + " is successful queued");
break;
case 2:
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else
{
System.out.println("\nDequeued customer: " +empList.getFirst());
empList.removeFirst();
}
System.out.println("\nNext customer in queue: " +empList.getFirst()+"\n");
break;
case 3:
System.out.println("\nThe Customer's names are: \n");
Iterator<Customer2> it = empList.iterator();
while (it.hasNext()) {
System.out.println("\nThe customers' names are: \n");
}
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
catch(InputMismatchException e) {
System.out.println("Please enter 1-5, 0 to quit");
sc.nextLine();
}
} while(choice != 0);
}
}
Look at your custom queue; you forgot to put the logic in your hasNext method. It will always return false. Therefore your addItems loop will never add any items to the queue.
If you need a hint towards how to do the hasNext(), my recommendation is to look at the size of your list and make a simple comparison.
public boolean hasNext() {
return false;
}
public void addItems(Queue1<? extends E> q) {
while (q.hasNext()) list.addLast(q.dequeue());
}
PS: I noticed that your code also shows the next in line. You might want to check if it's empty or hasNext() before that to not get a crash if the list was empty after that dequeuing.

Text game. How to use a bag?

Im wondering how i would go about using a bag in the game im making. The bag is supposed to hold 2 items that can be found in different rooms around the "map" and when both these items are found the game can be completed by finding the boss room. The bag is supposed to be its own java class. And how do i make the player activate these items?
rum4 and rum6 is the item rooms for anyone wondering.
(I dont want anyone to finish this game for me, i just want some help)
//Sorry for the swedish text.
//This is obviously not all of the code but the rest of it is not neccessary.
import java.util.Scanner;
public class Spel
{
public static void main(String[] args) {
Rum start = new Rum("Du är i en mörk och fuktig källare."," En källare. ");
Rum rum1 = new Rum("Du är mitt i en snöstorm!", "En snöstorm. ");
Rum rum2 = new Rum("Du hittade ett svärd!", "Ett hus. ");
Rum rum3 = new Rum("Du gick in i en fälla, slå över 3 för att fly norrut.", "En skog. ");
Rum rum4 = new Rum("Jaha... här fanns det ingenting.", "En äng. ");
start.north = rum1;
start.east = rum2;
start.south = rum3;
rum1.south = start;
rum1.east = rum4;
rum2.west = start;
rum2.north = rum4;
rum3.fälla = new trap();
rum3.north = start;
rum4.west = rum1;
rum4.south = rum2;
Rum current = start;
while(true) {
System.out.println(current);
System.out.println("Vart vill du gå? (n,s,v,o)");
char c = new Scanner(System.in).next().charAt(0);
switch(c) {
case 'n':
current = current.north;
break;
case 's':
current = current.south;
break;
case 'v':
current = current.west;
break;
case 'o':
current = current.east;
break;
}
if (current.fälla != null){
current.fälla.rulla();
}
// if (monster){
// System.out.println("Du kan nu döda monsteret");
if(current == null) {
System.out.println("Du ramlar av världen och dör †††");
System.out.println("Försök igen");
current = start;
}
}
I would create a class Bag with two Items
public class Bag {
Item item1;
Item item2;
}
public class Item {
<any item properties here>
}
In that case, I believe you need a class for Item, and types of items for the specific effects.
public abstract class Item {
public abstract void useItemOn(Entity target);
}
public class Entity {
private int maxHitPoints;
private int hitPoints;
private boolean isDead;
...
public void inflictDamage(int damage) {
hitPoints -= damage;
if(hitPoints < 0) {
this.isDead = true;
}
}
public void heal(int healPoints) {
hitPoints += healPoints;
if(hitPoints > maxHitPoints) {
this.hitPoints = maxHitPoints;
}
}
...
}
public class Player extends Entity {
...
}
public class Enemy extends Entity {
...
}
public Bomb extends Item {
#Override
public void useItemOn(Entity target) {
target.inflictDamage(20);
}
}
public Potion extends Item {
#Override
public void useItemOn(Entity target) {
target.heal(20);
}
}
Then
public class Bag {
private List<Item> items;
public Bag() {
this(new ArrayList<Item>());
}
public Bag(List<Item> items) {
this.items = items;
}
public List<Item> getItems() {
return items;
}
}
You can of course use smarter way to store Items to not mix them up, as you still need to figure out if something is a potion or a bomb.
But anyways, using it is simple, you need to take an item from the list, use it on an entity, then remove it from the list if it's a consumable.
Can someone find the boss room before they found the items? If no: how do you prevent it?
What you have to do when using my solution:
Create the bag at the begin of the game
Whenever one of the items was found: call the setFirstItemFound or setSecondItemFound method.
I don't know how you want to enable the boss room, but you can check if i should be findable by using the method "isBothItemsFound()"
Please notice, that this solution only works if there are only two items needed. If later like 10 items needed i would recommend you to make use of a hashTbale, a list or any equal "stacking" classes
public class Bag {
private static boolean firstItemFound = false;
private static boolean secondItemFound = false;
public Bag() {
super();
firstItemFound = false;
secondItemFound = false;
}
/* Sets the status to of the first Item to found */
public static void setFirstItemFound() {
firstItemFound = true;
}
/* Checks if the first item has been found */
public static boolean isFirstItemFound() {
return firstItemFound;
}
/* Sets the status to of the second Item to found */
public static boolean isFSecondItemFound() {
return secondItemFound;
}
/* Checks if the second item has been found */
public static void setSecondItemFound() {
secondItemFound = true;
}
/* Checks if both items has been found */
public static boolean isBothItemsFound() {
boolean bothItemsFound = false;
if (firstItemFound && secondItemFound){
bothItemsFound = true;
}
return bothItemsFound;
}
/* Sets the status to of both Items to not found */
public static void clearBag() {
firstItemFound = false;
secondItemFound = false;
}
}
You could maybe create some Player class to store all player data, and put Bag in it to hold items for example in:
HashMap<String, Item> itemsByName;
and always check when adding a new item to it if size 2 is not over exceeded.

how to access arraylist belonging to an object inside an arraylist

I have been stuck on the same problem for days and have googled everything I can think of and I give up. I am trying to write a program where you're supposed to first create a person object, and afterwards be able to give that person different types of belongings. I'm putting each created person in an arraylist and every person is supposed to have their own inventory which is also an arraylist. I just don't understand how to add items to a specific persons arraylist and how to print that arraylist. Do I have to create a new instance of the arraylist 'belongings' every time I create a new person? and how do I access a certain persons arraylist? Appreciate any sort of feedback because I am super noob.
import java.util.ArrayList;
public class Sakregister extends Programskelett{
public static ArrayList<Person> personList = new ArrayList<Person>();
protected boolean nextCommand(){
String command = readString("> ").toLowerCase();
switch(command){
case "print list":
printAll();
System.out.println("Program is running");
break;
case "print person":
printUser();
System.out.println("Program is running");
break;
case "create item":
newItem();
break;
case "create user":
newUser();
break;
case "print richest":
printRichest();
System.out.println("Program is running");
break;
case "crash":
initCrash();
break;
case "quit":
System.out.println("Program has terminated");
return true;
default:
System.out.println("Not a valid command");
}
return false;
}
private void printAll() {
}
private void initCrash() {
for (Person thisPerson : personList) {
for (Item thisItem : thisPerson.belongings)
if (thisItem.name == "Stock"){
((Stock) thisItem).setStockCrash(0);
}
}
}
private void printRichest() {
}
private void newUser() {
System.out.println("enter name: ");
String name = keyboard.nextLine();
Person newPerson = new Person(name);
personList.add(newPerson);
System.out.println("Person added to list");
}
private boolean newItem() {
System.out.println("enter item type: ");
String itemType = readString("> ").toLowerCase();
switch(itemType){
case "trinket":
addTrinket();
break;
case "stock":
addStock();
break;
case "appliance":
addAppliance();
return true;
default:
System.out.println("Not a valid item type");
}
return false;
}
private void addAppliance() {
System.out.println("Enter name of appliance: ");
String appName = keyboard.nextLine();
System.out.println("Enter initial price: ");
int appInitialPrice = keyboard.nextInt();
System.out.println("Enter level of wear: ");
int appWear = keyboard.nextInt();
Appliance newAppliance = new Appliance(appName, appInitialPrice, appWear);
System.out.println("Enter name of owner: ");
Object owner = keyboard.nextLine();
for(Person entry : personList)
if(entry.equals(owner))
entry.belongings.add(newAppliance);
}
private void addStock() {
System.out.println("Enter name of stock entry: ");
String stockName = keyboard.nextLine();
System.out.println("Enter amount: ");
int stockAmount = keyboard.nextInt();
System.out.println("Enter price: ");
int stockPrice = keyboard.nextInt();
Stock newStock = new Stock(stockName, stockAmount, stockPrice);
System.out.println("Enter name of owner: ");
String owner = keyboard.nextLine();
keyboard.nextLine();
for(Person entry : personList) {
if(entry.equals(owner)) {
entry.belongings.add(newStock);
}
}
}
private void addTrinket() {
System.out.println("Enter name of trinket: ");
String trinketName = keyboard.nextLine();
System.out.println("Enter number of gems: ");
int trinketGems = keyboard.nextInt();
System.out.println("Choose gold or silver: ");
String trinketMineral = keyboard.nextLine();
keyboard.nextLine();
Trinket newTrinket = new Trinket(trinketName, trinketGems, trinketMineral);
System.out.println("Enter name of owner: ");
String owner = keyboard.nextLine();
for(Person entry : personList)
if(entry.equals(owner))
entry.belongings.add(newTrinket);
}
private void printUser() {
// TODO Auto-generated method stub
}
protected void printMainMenu(){
System.out.println("Choose a command: ");
System.out.println("start");
System.out.println("quit");
}
public static void main(String[] args) {
Sakregister registerProgram = new Sakregister();
registerProgram.run();
}
}
public class Item{
protected String name;
public Item(String name){
this.name = name;
}
public String getItemName() {
return name;
}
import java.util.ArrayList;
public class Person{
public String name;
public String items;
public ArrayList<Item> belongings = new ArrayList<Item>();
public Person(String name){
this.name = name;
}
public String getName(){
return name;
}
public String toString() {
return "Name: " + name;
}
}
" I just don't understand how to add items to a specific persons arraylist and how to print that arraylist"
Your persons are in the personList, so i would use personList.get(n) to get the nth Person.
To add items to the belongings you can use personList.get(n).belongings.add(item).
To print an arraylist you can use a normal foreach loop:
for(Item i:personList.get(n).belongings){
System.out.println(i.getItemName());
}
Do I have to create a new instance of the arraylist 'belongings' every time I create a new person?
The ArrayList belongings is a field inside the Person class. When you create a person with the constructor all of its fields and variables are created in the memory. This happens every time you create a person, so every object (in your case person in the personList) has its own fields like the belongings list.
The new instance of the ArrayList<Item> belongings is already being created each time you create a new Person object, so you don't need to create it again anywhere. However, there is currently no getter for belongings, so you need to write one to access a given person's belongings. You want something like this:
public ArrayList<Item> getBelongings() {
return belongings;
}
You'll need to write a public method that accepts an Item object and adds it to the belongings of that Person. You shouldn't need help with writing another public method that calls System.out.println() on the belongings directly or iterates through them and prints them out.

Why is this sort array not working?

I have to sort an array here is the code I have. When I try to utilize Arrays.sort() I get tons of errors. Anyone know what I am doing wrong? This is really my first time sorting and using arrays with constructors.
import java.util.Scanner;
import java.util.Arrays;
public class CoffeeDriver {
//main method
public static void main (String[] args){
Item[] itemObject = new Item[] {
new Item("Donut", .75),
new Item("Coffee", 1.00),
new Item("Bagel", 1.25),
new Item("Milk", 1.50),
new Item("Water", 2.00)};
Scanner input = new Scanner(System.in);
String decision;
System.out.println ("Welcome to Wings Coffee Shop");
System.out.println ("We have a great list of tasty items on our menu.");
System.out.println ("Would you like to see these items sorted by");
System.out.println ("name or by price? (n/p): ");
decision = input.nextLine();
sortName(itemObject);
sortPrice(itemObject);
}
//method to sort by item name and display
public static void sortName (Item[] itemObject){
Arrays.sort(itemObject);
System.out.println(itemObject);
}
//method to sort by item price and display
public static void sortPrice (Item[] array){
Arrays.sort(array);
for (int i = 0; i < array.length; i++){
System.out.println (array[i]);
}
}
}
public class Item
{
private String itemName = ""; //setting up the name
private double itemPrice=0.0; //Setting price variable
public Item(String name, double price) //Constructor
{
itemName = name;
itemPrice = price;
}
public String getitemName() //retuns name
{
return itemName;
}
public double getitemPrice() //returns price
{
return itemPrice;
}
public void setitemName(String name) //sets name
{
itemName = name;
}
public void setitemPrice (double price) //sets price
{
itemPrice = price;
}
}
Your Item class doesn't implement compareable. The sort method states: "Furthermore, all elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array)."
But since you want to sort by two different things, implementing comparable won't get you very far, it's better to use a Comparator (http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html).
So your sort by name would look something like this (just replace the method part of compare(Item o1, Item o2) with the criteria you'd like the array to be sorted).
// method to sort by item name and display
public static void sortName(Item[] itemObject) {
Arrays.sort(itemObject, new Comparator<Item>() {
#Override
public int compare(Item o1, Item o2) {
return o1.getitemName().compareTo(o2.getitemName());
}
});
printArr(itemObject);
}
and your sortPrice like that:
// method to sort by item price and display
public static void sortPrice(Item[] array) {
Arrays.sort(array, new Comparator<Item>() {
#Override
public int compare(Item o1, Item o2) {
return Double.compare(o1.getitemPrice(), o2.getitemPrice());
}
});
printArr(array);
}
Also to print your results in a nice legible way it's generally a good idea to overwrite the toString() method in your class so that you can just write System.out.println(item); (toString is called automatically in that case).
Okay to get the content nicely printed we first add a toString() Method to your item class:
#Override
public String toString() {
return itemName + ": " + itemPrice;
}
That will just return the item's name and it's price when called. To print the array's content now nicely we'll just iterate through all it's members:
private static void printArr(Item[] arr) {
for(Item i : arr) {
System.out.println(i); // the same as System.out.println(i.toString()); - Java calls the toString method automatically in this case we you give it an object
}
}
Now we can just call this function everywhere you want to print the contents of an item array, like after sorting them!
Arrays.sort takes a Comparator which is used to perform the sort.
A Comparator used to find the difference between 2 items.
public static void sortName (Item[] itemObject){
Arrays.sort(itemObject, new Comparator<Item>() {
public int compare(Item a, Item b) {
if(a.getitemName() == null){
return b.getitemName() == null ? 0 : -1;
}
return a.getitemName().compareTo(b.getitemName());
}
});
}
public static void sortPrice (Item[] array){
Arrays.sort(array, new Comparator<Item>() {
public int compare(Item a, Item b) {
return Double.compare(a.getitemPrice(), b.getitemPrice());
}
});
}
You need to implement the compareTo method in your Item class, and declare it to implement the Comparable interface.
See How to use Comparable for an example.

Categories

Resources