So I need to grab the itemPrice part of the index and add them all together, but i'm not sure how to go about accessing that. Can I somehow use my getCost method from the GroceryItemOrder class and continuously add it to the totalCost in the GroceryList class, or do I need to access the itemPrice and quantity part of each stored object.
public class GroceryList {
public GroceryItemOrder[] groceryList = new GroceryItemOrder[0];
public int manyItems;
public GroceryList() {
final int INITIAL_CAPACITY = 10;
groceryList = new GroceryItemOrder[INITIAL_CAPACITY];
manyItems = 0;
}
//Constructs a new empty grocery list array
public GroceryList(int numItem) {
if (numItem < 0)
throw new IllegalArgumentException
("The amount of items you wanted to add your grocery list is negative: " + numItem);
groceryList = new GroceryItemOrder[numItem];
manyItems = 0;
}
public void add(GroceryItemOrder item) {
if (manyItems <= 10) {
groceryList[manyItems] = item;
}
manyItems++;
}
//
// #return the total sum list of all grocery items in the list
public double getTotalCost() {
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++ ) {
//THIS PART
}
return totalCost;
}
}
And this is GroceryItemOrder
public class GroceryItemOrder {
public String itemName;
public int itemQuantity;
public double itemPrice;
public GroceryItemOrder(String name, int quantity, double pricePerUnit) {
itemName = name;
itemQuantity = quantity;
itemPrice = pricePerUnit;
}
public double getcost() {
return (itemPrice*itemQuantity);
}
public void setQuantity(int quantity) {
itemQuantity = quantity;
}
public String toString() {
return (itemName + " " + itemQuantity);
}
}
Thanks for all the replies! I got it working and understand what's going on here now.
You first need to access an instance of GroceryItemOrder in the array and from there then access its itemPrice field like so,
groceryList[0].itemPrice
would give you the itemPrice of the first groceryListOrder in the groceryList array. If you want to use a method to do this instead, then add a getItemPrice method in your groceryListOrder class,
public getItemPrice() {
return itemPrice;
}
Then you can access each groceryListOrder's itemPrice in the array like so,
groceryList[0].getItemPrice()
would do the same as groceryList[0].itemPrice. If you wanna get the total cost of all the objects in the groceryList array, then use a loop to add all the itemPrice fields multiplied by the itemQuantity field (since it's the totalcost of each object being summed together) by using your getcost method,
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++) {
totalCost += groceryList[i].getcost();
}
First of all you should encapsulate all fields ofGroceryItemOrder class, so all the fields should be private member of the class and then use their setter/getter methods to access them in GroceryList.
Secondly, this implementation has a bug. The second constructor gets numItem as input and initialize array size accordingly. But, add method does not look at the real size and that might cause invalid array index exception. Consider this code:
GroceryList list = new GroceryList(2);
for (int i=0; i<10; i++)
list.add(new GroceryItemOrder("grocery", 5, 10));
The exception will be occurred when i=2
This works for me, you would need to set static GroceryItemOrder[] groceryList = new GroceryItemOrder[0]; as well:
//
// #return the total sum list of all grocery items in the list
public static double getTotalCost() {
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++ )
{
totalCost += groceryList[i].getcost();
}
return totalCost;
}
Related
I have two classes here:
public class Invoice {
ArrayList<Double> ItemPrices= new ArrayList<Double>();
ArrayList<Boolean> ItemIsPet = new ArrayList<Boolean>();
ArrayList<Integer> ItemQuantitys = new ArrayList<Integer>();
public void add(Item anItem){
}
public static void main(String args[]){
int counter = 0;
boolean pet;
Scanner s = new Scanner(System.in);
do {
System.out.println();
System.out.print("Item " + counter+1 + ":");
System.out.println();
System.out.print("Please enter the item's price: ");
double inputprice = s.nextDouble();
System.out.println();
System.out.print("Is this item a pet? (Y/N): ");
String inputIsPet = s.next();
if (inputIsPet.equals('Y')){
pet = true;
}
else {
pet = false;
}
System.out.println();
System.out.print("What is the quantity of this item?: ");
int inputquantity = s.nextInt();
Item newItem = new Item(inputprice, pet, inputquantity);
counter += 1;
} while (true);
}
}
And here is the second class:
public class Item {
Invoice Inv = new Invoice();
public Item(double price, boolean isPet, int quantity){
}
}
My question is for this line right here:
Item newItem = new Item(inputprice, pet, inputquantity);
So I have those 3 necessary arguments from the user input so that I can make a new object newItem of type item, but my question is once I have object newItem, how can I access those inputted arguments? My assignment is forcing me to implement this particular "add" method:
public void add(Item anItem)
Basically, the way I want to use this method is to take the inputted arguments from here:
Item newItem = new Item(inputprice, pet, inputquantity);
and have the "add" method access them, and from there put them into these arrays:
ArrayList<Double> ItemPrices= new ArrayList<Double>();
ArrayList<Boolean> ItemIsPet = new ArrayList<Boolean>();
ArrayList<Integer> ItemQuantitys = new ArrayList<Integer>();
But how do I access the parts of the object newItem? Do I have to modify my constructor in some way?
Do I have to modify my constructor in some way?
Yes, you need to save incoming values into instance fields.
public class Item {
private final double price;
private final boolean isPet;
private final int quantity;
public Item(double price, boolean isPet, int quantity) {
this.price = price;
this.isPet = isPet;
this.quantity = quantity;
}
}
How can I access those inputted arguments?
Then you can write a getter for each field you want to access to.
public double getPrice() {
return price;
}
How do I access the parts of the object newItem?
Now you can.
double price = newItem.getPrice();
I have to write a program that uses two classes to create a grocery list. The first class creates an array to hold the values gotten from the second class. The array holds grocery items which have a name, quantity, and price value. I have a function that is supposed to get a total cost of everything in the array, but for some reason the function is only adding the last item that is added to the array to itself. Here's my code:
public class GroceryList {
private GroceryItemOrder[] groceryList = new GroceryItemOrder[0];
private int numofEntries;
public GroceryList()
{
this.groceryList = new GroceryItemOrder[10];
this.numofEntries = 0;
}
public void add(GroceryItemOrder item)
{
if(numofEntries == 10)
{
System.out.println("The list is full.");
}
else
{
groceryList[numofEntries] = item;
numofEntries++;
}
}
public double getTotalCost()
{
double totalCost = 0;
double newCost = 0;
for(int size = 0; size < numofEntries; size ++)
{
newCost = groceryList[size].getCost();
totalCost = newCost + totalCost;
}
return totalCost;
}
public class GroceryItemOrder {
private static double pricePerUnit;
private static int quantity;
private String name;
public GroceryItemOrder(String name, int quantity, double pricePerUnit)
{
this.name = name;
this.quantity = quantity;
this.pricePerUnit = pricePerUnit;
}
public static double getCost()
{
return (quantity * pricePerUnit);
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public static void main(String[] args)
{
GroceryList newList = new GroceryList();
newList.add(new GroceryItemOrder("cookies", 1, 1.50));
newList.add(new GroceryItemOrder("cheese", 2, 1.0));
newList.add(new GroceryItemOrder("bread", 1, 5.0));
System.out.println(newList.getTotalCost());
}
}
In the function I was trying to use a for loop that would run through the array one element at a time and take whatever values were stored into the element and store it into a new object. I feel like I'm heading in the right direction but can't figure out where the issue is with the function. Can anyone see where my issue is, or at least give me some advice on how I can begin to attempt to fix the issue?
2 of your 3 variables in GroceryItemOrder are static, which means only one variable for the entire class, not one for each instance. Each new instance overwrites the values set by the previously created instance.
Make all of those instance variables not static:
private double pricePerUnit;
private int quantity;
private String name;
The static modifier to quantity and pricePerUnit makes no sense if you want to have some variety in your grocery. What happens is that each time you call the constructor or GroceryItemOrder, you change those two static fields, so if affects the total price of all the previous orders created. The rest is fine even if it could be more concise sometimes.
So I have to find the minimum in an array in Java, but with that I have to print out the corresponding names that go with the minimum in another parallel array. Inside my for loop where I find the minimum, I have a variable place that I set equal to my counter variable from the for loop when the minimum is changed. But every time I print out the name, it prints out the first name in the array instead of the name in the place holder.
public double getMinimum(double[] money)
{
double lowest = money[0];
for (int p = 0; p < money.length; p++)
{
if (money[p] < lowest)
{
lowest = money[p];
place = p;
}
}
return lowest;
}
Theres the for loop within my programmer-defined class that finds the minimum.
public String getFirstNameMin(String[] firstName)
{
String minFirstName;
minFirstName = firstName[place];
return minFirstName;
}
This is the code I'm using to figure out the first name from the first names array at that place. What am I doing wrong? I'm kinda new to Java, but I did all this array stuff in C++ before, so idk if I am missing something very simple, or its different in Java.
I would say try making a separate class for this that contains the user and the money:
public class User {
private double money;
private String fname;
private String lname;
//getters/setters/constructors
}
Then from there you can simply compare the accounts:
public User getMinimum(User[] users) {
if (users.length <= 0) {
return null;
}
User lowest = users[0];
for (int i = 1; i < users.length; i++) {
if (users[i].getMoney() < lowest.getMoney()) {
lowest = users[i];
}
}
return lowest;
}
Try this:
public int getMinIndex(double[] money)
{
double min = money[0];
int minIndex = 0;
for (int p = 0; p < money.length; p++)
{
if (money[p] < min)
{
min = money[p];
minIndex = p;
}
}
return minIndex;
}
public static void main(String[] args)
{
double[] money;
String[] name;
//... init your arrays here!
int index = getMinIndex(money);
System.out.println("Min money = " + money[index] + "; name = " + name[index]);
}
However, following an object oriented approach rogues solution is much nicer!!!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am making a program where I have a class called GroceryItem, Another called GroceryList, and the third is main method which will run the program.
I have done alot in this program, but I am stuck now. Please have a look on my code and help me.
GroceryItem Class:
public class GroceryItem {
private String name;
private double pricePerUnit;
private int quantity;
public GroceryItem(int quantity, String name, double pricePerUnit) {
this.name = name;
this.pricePerUnit = pricePerUnit;
this.quantity = quantity;
}
public double getCost() {
return (this.quantity * this.pricePerUnit);
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
GroceryList Class:
public class GroceryList {
private GroceryItem[] list = null;
int num;
public GroceryList() {
list = new GroceryItem[10];
this.num = 0;
}
// Constructs a new empty grocery list.
public void add(GroceryItem item) {
list.add(item);
}
// Adds the given item order to this list, if the list is not full (has
// fewer than 10 items).
public double getTotalCost() {
double totalcost = 0;
for(int i = 0; i < list.length; i++){
totalcost += getGroceryItemOrder(getCost());
}
return totalcost;
}
// Returns the total sum cost of all grocery item orders in this list.
}
Main Method:
public static void main(String[] args) {
GroceryList list = new GroceryList();
GroceryItem carrots = new GroceryItem(5,"Carrots", 0.40);
list.add(carrots);
GroceryItem apples = new GroceryItem( 4,"Apples", 0.15);
list.add(apples);
GroceryItem rice = new GroceryItem( 1,"Rice", 1.10);
list.add(rice);
GroceryItem tortillas = new GroceryItem(10,"Tortillas", .05);
list.add(tortillas);
GroceryItem strawberries = new GroceryItem(1,"Strawberries", 4.99);
list.add(strawberries);
GroceryItem chicken = new GroceryItem( 1,"Chicken", 5.99);
list.add(chicken);
GroceryItem lettuce = new GroceryItem( 1,"Lettuce", 0.99);
list.add(lettuce);
GroceryItem milk = new GroceryItem( 2,"Milk", 2.39);
list.add(milk);
GroceryItem yogurt = new GroceryItem( 3,"Yogurt", 0.60);
list.add(yogurt);
GroceryItem chocolate = new GroceryItem(1,"Chocolate", 3.99);
list.add(chocolate);
}
}
You are trying to use the method add to add things to an array.
You should either use an ArrayList or similar data structure, or add items using an index:
list[ index++ ] = item
The reason is that simple arrays don't have an add method. ArrayList, and several other collection classes, do.
Also, in your original code, you have the line:
totalcost += getGroceryItemOrder(getCost());
There is no method getGroceryItemOrder(...) defined in this code. And, in this form, it will call getCost() on the GroceryItemList class. GroceryItemList has no such method, so you get an error.
You want to call getCost() on the current list item, so the line you need is:
totalcost += list[i].getCost();
Use this to add your Grocery element.
GroceryList class
public class GroceryList {
List<GroceryItem> list = null;
int num;
public GroceryList() {
list = new ArrayList<GroceryItem>();
this.num = 0;
}
// Constructs a new empty grocery list.
public void add(GroceryItem item) {
list.add(item);
System.out.println("Added Grocery :::: >>>> NAME:" +item.getName()+ " ::::: PRICE PER UNIT: "+item.getPricePerUnit()+" :::::: QUANTITY: "+item.getQuantity()+" ::::: FINALCOST: "+(item.getQuantity()*item.getPricePerUnit()) );}
// Adds the given item order to this list, if the list is not full (has
// fewer than 10 items).
public double getTotalCost() {
double totalcost = 0;
for(int i = 0; i < list.size(); i++){
totalcost += list.get(i).getCost();
}
return totalcost;
}
// Returns the total sum cost of all grocery item orders in this list.
}
/// Add this function as toString class
#Override
public String toString() {
return "GroceryList [list=" + list + ", num=" + num + "]";
}
// add a function for finding cost per item like this
public HashMap<String,Double> getCostPerItem(int i) {
HashMap<String, Double> itemPriceName= new HashMap<String, Double>();
itemPriceName.put(list.get(i).getName(),
(list.get(i).getPricePerUnit()*list.get(i).getQuantity()));
return itemPriceName;
}
// IN main function you can call above specified function
for(int i=0;i<list.list.size();i++) {
System.out.println("Cost Per Item "+list.getCostPerItem(i));
}
Having problems linking this program to this class. The program takes in a set of String + double arrays and goes through a series of sorts to yield a result. Our instructions are to sort then by name and sort then by price.
Main problem is that the Strings are displaying as hexadecimal eg(Item#4fjipe) etc.
Second problem is my sorts. I just have no idea how to make them work. Please help if at all possible. I will include both the class and the program. Bear in mind they are 2 different .java working together. I'm a beginner, by the way.
public class Item
{
private String itemName; // hold the name of the item
private double itemPrice; // hold the price of the item
public Item(String s, double p) // Constructor
{
itemName = s;
itemPrice = p;
}//end constructor
public void setName(String n)
{//method to set the item name
itemName = n;
}//end method
public String getName()
{//method to get the item name
return itemName;
}//end method
public double setPrice(double p1)
{//method to set the price of the item
itemPrice = p1;
return itemPrice;
}//end method
public double getPrice()
{//method to get the price of the item
return itemPrice;
}//end method
}//end class
AND NOW THE OTHER BEGINS. THIS ONE IS STILL A HOT MESS.
import javax.swing.*;
import java.util.Arrays;
public class CoffeeDriver
{
public static void main (String[] args)
{
Item[] itemArray = new Item[5]; // Array of type Item declaration
boolean loopControl = false; //variable for control of our loop
while (!loopControl)
{
itemArray[0] = new Item("Coffee", 1.00);
itemArray[1] = new Item("Water", 2.00);
itemArray[2] = new Item("Milk", 1.50);
itemArray[3] = new Item("Bagel",1.25);
itemArray[4] = new Item("Donut", 0.75);
String input = JOptionPane.showInputDialog(null, "Welcome to Wings Coffee Shop. We have a great list items on our menu. \nWould you like to see these items sorted by name of by price? (n/p):");
if(input.equals("n"))
{
sortName(itemArray);
JOptionPane.showMessageDialog(null, itemArray);
}//end if
else if(input.equals("p"))
{
sortPrice(itemArray);
JOptionPane.showMessageDialog(null, itemArray);
}
else
{
loopControl = true;
}
}//end while
}//end main
public static void sortName(Item[] itemArray)
{
int n = itemArray.length;
Item temp = new Item("",0);
for (int i =0; i < n; i++)
{
for(int j =1; j<(n-1); j++)
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
if(itemArray[j+1] == itemArray[j])
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
itemArray[j+1].setPrice(itemArray[j].getPrice());
itemArray[j+1].setName(itemArray[j].getName());
itemArray[j].setPrice(temp.getPrice());
itemArray[j].setName(temp.getName());
temp = itemArray[j+1];
itemArray[j+1] = itemArray[j];
itemArray[j] = temp;
JOptionPane.showMessageDialog(null, itemArray);
}//end if
}//end inner for
}//end outer for
}//end sortName
public static void sortPrice(Item[] itemArray)
{
int n = itemArray.length;
Item temp = new Item("",0);
for (int i =0; i < n; i++)
{
for(int j =1; j<(n-1); j++)
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
if(itemArray[j+1] == itemArray[j])
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
itemArray[j+1].setPrice(itemArray[j].getPrice());
itemArray[j+1].setName(itemArray[j].getName());
itemArray[j].setPrice(temp.getPrice());
itemArray[j].setName(temp.getName());
temp = itemArray[j+1];
itemArray[j+1] = itemArray[j];
itemArray[j] = temp;
JOptionPane.showMessageDialog(null, itemArray);
}//end if
}//end inner for
}//end outer for
}//end sortPrice
}//end class
You need to override the toString method in your Item class. You could use:
#Override
public String toString() {
return "Item [itemName=" + itemName + ", itemPrice=" + itemPrice + "]";
}
As you need to have 2 separate methods to sort by name and by price, you could use a custom comparator for both cases, using the appropriate field to compare against. Have a look at Arrays.sort() for doing the actual sorting.
'Item#4fjipe' is the object reference as provided by the default implementation of Object.toString() - read the API for reference.
A hexadecmial literal in Java start swith 0x, e.g. 0x10.
For your specific problem, you have a data object that you wish to sort in 2 different ways. Read the API documentation for Comparator and Comparable. Then check the Collections API to see which collections might offer you sorting.