get specific value from arraylist element - java

Sorry if this is an easy answer or has been answered, but have searched and couldnt find anything. I am currently creating a supermarket checkout line with the products in a DefaultListModel, each product having a name, price, weight and code as shown below
public class Product {
private String name;
private double weight;
private double price;
private int code;
public Product (){
}
public Product (String Name, double kg, double pounds, int id){
name = Name;
weight = kg;
price = pounds;
code = id;
public String toString (){
return name + " - " + "£" + price + " Product # " + code;
and the products put into a list
public class productList extends DefaultListModel {
public productList (){
super();
}
public void addProduct (String name, double weight, double price, int code){
super.addElement(new Product(name, weight, price, code));
this has been used in the GUI for the checkout in the code segments as follows
private DefaultListModel defaultMainList = new DefaultListModel();
//other code
currentBasket.setModel(defaultMainList); //currentBasket is name of jlist
productsList = new productList();
productsList.addProduct("bananas", 0.5, 0.99, 1);
productsList.addProduct("apples", 0.8, 1.39, 2);
//etc etc, other products emitted
mainCheckoutList.setModel(productsList);
//unimportant code
addBasketItem = new JButton();
getContentPane().add(addBasketItem);
addBasketItem.setText("Add >");
addBasketItem.setBounds(215, 108, 62, 31);
addBasketItem.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e){
defaultMainList.addElement(productsList.getElementAt(mainCheckoutList.getSelectedIndex()));
mainTillPrice.setText((defaultMainList.toString()));
this current code adds the item from the jlist on the left (main checkout list, which is my list of available products) to the jlist on the right which is my basket. It also adds the entire string of characters in the right list to the jtextfield called mainTillPrice, i want to know if there is any way just to add the price, eg. for the bananas object add 0.99, and then with subsequent items added add their prices as well to keep a running total. Any help would be appreciated and again sorry for any problems in explanation or code, i am fairly new.

Well, I wouldn't be using defaultMainList.toString(). You will need to get the Product which is been added, get the price of the Product and add it to the current tally. This value would then need to be added to the mainTillPrice text field
public void actionPerformed (ActionEvent e){
Product product = (Product)mainCheckoutList.getSelectedItem();
defaultMainList.addElement(product);
runningTally += product.getPrice();
mainTillPrice.setText(NumberFormat.getCurrencyInstance().format(runningTally));
This will require you to create an instance field called runningTally and assumes you have a method getPrice in your Product

Related

RESTful web service: How can I take this data without printing out the other

I want to just take the data from menSize and its price but it keep printing out the womenSize eventhought it doesn't add anything in it.
Do I need to seperate menSize class and womenSize class or is there any way to fix it:
Here is my Getter and Setter of Shoes class:
private double menSize;
private double price;
private double womenSize;
This is my ShoesController class:
#GetMapping("menshoes")
public List getMenShoes() {
List<Shoes> menShoesList = new ArrayList<>(); // Create ArrayList holding men sizes
while (true) {
for (double i = 2; i <= 12; i += 0.5) { // set sizes : 2 , 2.5 ,... until 12
Shoes shoe = new Shoes();
shoe.setMenSize(i);
shoe.setPrice(4); // Set price to $4
menShoesList.add(shoe); // add size to ArrayList
}
return menShoesList;
}
}
#GetMapping("womenshoes")
public List<Shoes> getWomenShoes() {
List<Shoes> womenShoesList = new ArrayList<>(); // Create ArrayList holding women sizes
while (true) {
for (double i = 5; i <= 12; i += 0.5) { // set sizes : 5, 5.5 , ... until 12
Shoes shoe2 = new Shoes();
shoe2.setWomenSize(i);
shoe2.setPrice(4); // Set price to $4
womenShoesList.add(shoe2); // add size to ArrayList
}
return womenShoesList;
}
}
The output when I search for localhost:8080/menshoes are (I just take 3 for examples):
[{"menSize":2.0,"price":"$4.00","womenSize":0.0},{"menSize":2.5,"price":"$4.00","womenSize":0.0},{"menSize":3.0,"price":"$4.00","womenSize":0.0}
I see 2 options: Either having 2 classes, one for each type of shoe
or defining the type inside your class and not having two sizes of which one is always empty. Since you have a limited amount of possible types I suggest you use an enum for modeling the type.
public enum ShoeType {
MEN,
WOMEN
}
public class Shoe {
private ShoeType type;
private double size;
private double price;
// getter, setter, constructor...
}
Example of this comment:
"I would highly recommend only having one [class] type similar to what you suggested"
Default constructor
public class Shoes
{
this(null, 0, 0);
}
Overloaded constructor
public class Shoes(String gender, double size, double price)
{
this.gender = gender;
this.size = size;
this.price = price;
}

How to add an Object to an ArrayList

I recently changed my Locale constructor to take in an array called Item instead of just an item name and now I'm having some difficulties with taking an item in my game. This is a text adventure game where the player can move around the map and pick up items that are in the rooms. I am getting the error: "The method add(String) in the type ArrayList is not applicable for the arguments (Item)". I'm not sure how to fix this issue.
Thank you for all help!
Here is my code:
static int currentLocation = player1.currentRoom;
//Items {itemName, itemDes}
static Item[] items = {
new Item ("map","A layout of your house."),
new Item ("battery", "A double A battery."),
new Item ("flashlight", "A small silver flashlight."),
new Item ("key", "This unlocks some door in your house."),
};
//Locations {roomName, description, Item}
static Locale[] locales = {
new Locale("bedroom","You see the outline of a bed with your childhood stuffed bear on it.",items[0]),
new Locale("hallway","A carpeted floor and long pictured walls lie ahead of you.",null),
new Locale("kitchen","The shining surface of your stove reflects the pale moonlight coming in the window over the sink.",items[1]),
new Locale("bathroom","You find yourself standing in front of a mirror, looking back at yourself.",items[2]),
new Locale("living room","You stub your toe on the sofa in the room, almost falling right into the TV.",null),
new Locale("dining room","You bump the china cabinet which holds your expensive dishes and silverware.",items[3]),
new Locale("office","The blinking light from the monitor on your desk can be seen in the dark",null),
new Locale("library","The smell of old books surrounds you.",null),
new Locale("basement","You reach the top of some stairs and upon descending down, you find the large metal generator.",null),
};
//Take
else if(response.equalsIgnoreCase("T")){
Locale locale = locales[currentLocation];
// check if the locale has an item.
if(locale.item != null){
// create an "ArrayList" with all the items from the players inventory or an empty one if the inventory is "null"
ArrayList<String> inventory;
if(player1.inventory != null){
inventory = new ArrayList<String>(Arrays.asList(player1.inventory));
}
else{
inventory = new ArrayList();
}
// add the item to the list and set the list as the player's inventory by converting it to an array.
inventory.add(locale.item);
player1.inventory = inventory.toArray(new String[inventory.size()]);
System.out.println("\tA " + locale.item + " was added to the inventory");
System.out.println("\n\tYou can view your inventory by pressing 'I'.");
System.out.println("\n\tFive points have also been added to your score.");
player1.score += 5;
System.out.println("\n\tThis is your current score: "+player1.score);
locale.item = null;
}
// this locale doesn't have an item.
else{
System.out.println("\tThere is no item to pick up");
}
break;
}//End of Take
This is my Locale class:
public class Locale {
//Locale must have name, description, and Item
public static int roomNumber;
public String roomName;
public String description;
public Item item;
public Locale(String roomName, String description, Item item){
this.roomName = roomName;
this.description = description;
this.item = Item;
}
}
This is my Item class:
public class Item {
//item must have a name and a description (both strings)
public String itemName;
public String itemDes;
public Item (String itemName, String itemDes){
this.itemName = itemName;
this.itemDes = itemDes;
}
}
item[i] references an Item object. If Item is a parameter for your Locale constructor i don't see why this wouldn't work. Are there any specific error messages?

is this the correct use of aggregation

I want to simulate a cash register system. At the end of the transaction, the receipt would be displayed on the monitor. I've created a class called Receipt, it contains info about items purchased by the customer, subtotal, and customer's name. So, in the Receipt class, I created an ArrayList of product and a buyer object as instance variables. The toString() function would return a nice formatted string.
I am not sure if I should use ArrayList as an instance variable and I don't know if aggregation is the best choice here.
import java.util.ArrayList;
public class Receipt {
private ArrayList<Product> purchased_products;
private double total_price;
private double total_with_tax;
private Buyer buyer;
public Receipt(Buyer buyer, ArrayList<Product> purchased_products,
double total_price, double total_with_tax) {
this.purchased_products = new ArrayList<>(purchased_products);
this.total_price = total_price;
this.buyer = buyer;
this.total_with_tax = total_with_tax;
}
#Override
public String toString() {
String content = "Receipt: \nConvenience Store\n";
content += "Balance Summary:\n";
for (Product product : purchased_products) {
content += product + "\n";
}
content += String.format("%d Subtotals: $%.2f\nAmount Paid: $%.2f\n", purchased_products.size(), total_price,
total_with_tax);
content += buyer.toString() + "\n";
content += "Thank you for shopping with us. Have a wonderful day!\n";
return content;
}
}
Everything looks fine and you are doing it correct almost.
A small correction in constrctor is you need not to have a new array list again.
Just
this.purchased_products = purchased_products;
Is enough.

How to sum an attribute's object from a stack of objects?

I have a class car with constructor as
public car (String name, int numberOfCars, int price) {}
Then, in my main, I created stack as:
Stack<car>carStack = new Stack<car>();
carStack.push("Honda", 200, 19000));
carStack.push("Toyota", 300, 18000));
carStack.push("BMW", 150, 40000));
How can I get the price of 500 cars (150 BMW + 300 Toyota + 50 Honda) from this stack?
Steps:
Iterate through the Stack with a for loop. Stack implements the Iterable interface, and so a for-each loop is probably the easiest to use: for (Car myCar: carStack) {...}
call getPrice() on the items in the loop
add this to a sum variable that has been declared before the loop
Q.E.D.
As an aside, to have your code comply with Java naming standards, your car class should be renamed Car. Class and interface names should begin with an upper case letter.
Since someone else is showing off code, here's my big whoop code snippet:
double price = 0.0;
for (Car myCar: carStack) {
price += myCar.getPrice();
}
You can iterate your stack within a foreach-loop:
double price = 0.0;
for(Car c : stack)
{
price += c.getPrice();
}
Or you can iterate your stack within a while-loop:
Iterator<Car> iter = carStack.iterator();
double price = 0.0;
while (iter.hasNext()) {
price += iter.next().getPrice();
}
If you're using Eclipse Collections, you can use a MutableStack which has the method sumOfInt().
Car honda = new Car("Honda", 19000);
Car toyota = new Car("Toyota", 18000);
Car bmw = new Car("BMW", 40000);
MutableStack<Car> carStack =
ArrayStack.newStackFromTopToBottom(honda, toyota, bmw);
long price = carStack.sumOfInt(new IntFunction<Car>()
{
#Override
public int intValueOf(Car eachCar)
{
return eachCar.getPrice();
}
});
Assert.assertEquals(77000, price);
The question mentions that each car has a number of occurrences. Perhaps a Bag would be a more appropriate data structure than a StackIterable. A Bag keeps track of items and how many times the item occurs in the Bag. It would mean deleting the numberOfCars field from Car.
MutableBag<Car> carBag = HashBag.newBag();
carBag.addOccurrences(honda, 200);
carBag.addOccurrences(toyota, 300);
carBag.addOccurrences(bmw, 150);
long price = carBag.sumOfInt(new IntFunction<Car>()
{
#Override
public int intValueOf(Car eachCar)
{
return eachCar.getPrice();
}
});
Assert.assertEquals(15200000, price);
When Java 8 is released, we can replace the anonymous inner class with a lambda or method reference. Here's what the code will look like with a method reference.
long price = carBag.sumOfInt(Car::getPrice);
If price were a double instead of an int, we'd just need to replace sumOfInt() with sumOfDouble().
long price = carBag.sumOfDouble(Car::getPrice);
Note: I am a committer for Eclipse collections.
int total = 0;
while(!cars.isEmpty()) {
total += cars.pop().getTotal();
}
Then Car's getTotal:
public double getTotal() {
return price * quantity;
}
Or if you want to preserve stack, do the foreach that others have mentioned.

Incrementing value in a Map (JAVA)

I'm having a problem with this home work assignment. I can handle the syntax, but not the logic. Could you provide me some tips.
What I'm trying to achieve is that the add method would increase the amount of products by using the increaseAmount method. Now it resets the value of amount to "1" every time I call the method. What makes this complicated is that I'm not allowed to use any other private variables than already used.
private Map<String, Purchase> shoppingCart = new HashMap<String, Purchase>();
public void add (String product, int price) {
Purchase purchase = new Purchase (product, 1, price);
//the line abowe returns the value back to 1 which I don't want.
if(shoppingCart.containsKey(product)) {
shoppingCart.put(product, purchase);
purchase.increaseAmount();
}
else {
shoppingCart.put(product, purchase);
The product constructor:
public Ostos(String product, int amount, int price) {
Code for the increaseAmount method:
private int amount;
public void increaseAmount() {
this.amount = (this.amount + 1);
Don't create a new purchase at the beginning only create it if it's not already there
public void add (String product, int price) {
if(shoppingCart.containsKey(product)) {
Purchase purchase = shoppingCart.get(product);
purchase.increaseAmount();
//You might have to put the purchase back into the cart I'm not sure
}
else {
Purchase purchase = new Purchase (product, 1, price);
shoppingCart.put(product, purchase);
}
You have to retrieve the value from shoppingCart and then increment the amount. You're never calling shoppingCart.get, so you're replacing the value each time by blindly putting the new purchase object into the map.

Categories

Resources