At the end of my for loop, Id like to print out all the objects in the array. I used a generate toString with string builder from Source, however, after the loop is done executing, it prints out the default values of variables Item:
[Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], null]
heres my code
public class Item {
static Item list[]=new Item [7];
public static int x = 0;
public static String setName;
public static double setPrice;
public static int setPrioirty;
private int priority=-1;
private double price;
private String name;
Item(){
priority=-1;
price=0;
name="No Name yet.";
}// default constructor.
public Item(int i, double j, String k) {
setItem(i,j,k); //constructor with 3 arguments.
}
public void setItem (int i, double j, String k){ // setting item with 3 attributes.
setPriority(i);
setPrice(j);
setName(k);
}
public void setName(String k) { //setting individual attributes in item.
// TODO Auto-generated method stub //page 378
name=k;
}
public void setPrice(double j) {//setting individual attributes in item.
// TODO Auto-generated method stub
if (j<0||j>100){
System.out.println("Error: price is too low or high");
}
else
price=j;
}
public void setPriority(int i) {//setting individual attributes in item.
// TODO Auto-generated method stub
priority =((i>=0&&i<7)?i:0);
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
public double getPriority(){
return priority;
}
public static void add(Item itemObject) {
if (x<7)
{
list[x]=itemObject;
System.out.println("Item added at index " + x);
x++;
}
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Item [getPrice()=").append(getPrice()).append(", ");
if (getName() != null)
builder.append("getName()=").append(getName()).append(", ");
builder.append("getPriority()=").append(getPriority()).append("]");
return builder.toString();
}
}
main
import java.util.Arrays;
import java.util.Scanner;
import java.util.Set;
public class homework3main extends Item {
#SuppressWarnings("static-access")
public static void main(String[] args) {
//item list[]=new item [7]; // array of objects
Scanner keyboard= new Scanner(System.in);
for(int x=1; x<7;x++){
Item itemObject=new Item ();
//Item itemObject=new Item (setPrioirty,setPrice,setName);
//creating new object with 3 variables, name, price, priority
//list[x]=new Item();// is this right?
System.out.println("Enter an item you want to add to your list "+ x);
list[x].setName=keyboard.next();
System.out.println("Enter a price "+x);
list[x].setPrice=keyboard.nextDouble();
System.out.println("Enter the priority of the item "+x);
list[x].setPrioirty=keyboard.nextInt();
//item itemObject=new item (setPrioirty,setPrice,setName);
list[x].add(itemObject);
}
System.out.println(Arrays.toString(list));
My conditional statements dont work either in my Set methods. Cant understand why those dont work, they are pretty straight forward.
you appear to have several structural issues with the code so here is what i think it should be:
import java.util.Arrays;
import java.util.Scanner;
public class Item {
//the properties of an Item
private int priority;
private String name;
private double price;
//default constructer
public Item() {
priority = -1; //fill with default values
price = 0.0;
name = "No name yet";
}
//constructer with all fields given
public Item(int priority, String name, double price) {
this.priority = priority; //there are two instances of each variable
this.name = name; // use 'this.' to distinguish them
this.price = price;
}
// all getters simply will return the corresponding field
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
//priority must be between 0 and 7
if (priority >= 0 && priority <= 7) {
this.priority = priority;
} else {
//otherwise default to 0
this.priority = 0;
}
}
public String getName() {
return name;
}
public void setName(String name) {
//no constraints on the name so simply assign it
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
//price between 0 and 100 inclusive
if (price >= 0) {
if (price <= 100) {
this.price = price;
} else {
//use System.err for errors
// used nested ifs so you can tell if price is to high or low
//otherwise it is a bit ambiguous
System.err.println("Error: price to high");
}
} else {
System.err.println("Error: price to low");
}
}
//your tostring is fine
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Item [getPrice()=").append(getPrice()).append(", ");
if (getName() != null) {
builder.append("getName()=").append(getName()).append(", ");
}
builder.append("getPriority()=").append(getPriority()).append("]");
return builder.toString();
}
//just put your main here
//if you can't then put it in a class but don't sub-class this class
public static void main(String[] args) {
//put your list declaration here
//it doesn't quitemake sense for the Item calss to have a field
//called list in this instance
Item[] list = new Item[7];
Scanner keyboard = new Scanner(System.in);
//i is the most commonly used variable for 'for' loops
for (int i = 1; i <= list.length; i++) {
//create a new item
Item anItem = new Item();
//call your methods on that object to set its fields
System.out.println("Enter an item you want to add to your list " + i);
anItem.setName(keyboard.next());
System.out.println("Enter a price " + i);
anItem.setPrice(keyboard.nextDouble());
System.out.println("Enter the priority of the item " + i);
anItem.setPriority(keyboard.nextInt());
//use the var i for the position
//remember to subtract 1 since arrays start at 0 but i starts at 1
list[i-1] = anItem;
}
System.out.println(Arrays.toString(list));
}
}
In your condition
j < 0 && j > 100
How can j both be smaller than 0 and greater than 100? You need ||.
In your methods
System.out.println("Enter an item you want to add to your list "+ x);
list[x].setName=keyboard.next();
System.out.println("Enter a price "+x);
list[x].setPrice=keyboard.nextDouble();
System.out.println("Enter the priority of the item "+x);
list[x].setPrioirty=keyboard.nextInt();
you are setting the static fields of the Item class, not the fields of the instance. Either use the setters you have or use the constructor. For example
Item itemObject = new Item ();
System.out.println("Enter an item you want to add to your list "+ x);
itemObject.setName(keyboard.next());
System.out.println("Enter a price "+x);
itemObject.setPrice(keyboard.nextDouble());
System.out.println("Enter the priority of the item "+x);
itemObject.setPriority(keyboard.nextInt());
list[x] = itemObject;
You're completely overusing setters by the way. Go through this tutorial.
Related
I have two classes: Position and Order. In Position class, fields like: name, price. In Order class field: quantity. My problem is how to display: name, price and quantity together in Order class. I thought about delete arraylist and make another one with position and quantity but I doubt it would help me.
package programming.com.pl;
public class Position {
private String name;
private double price = 0;
public Position(String name, double price){
this.name = name;
this.price = price;
}
public double getPrice() {
return price;
}
public String toString(){
String str = String.format("%4s,%4s", name,price);
return str;
}
}
public class Order {
private int quantity;
final private ArrayList<Position> positions = new ArrayList<Position>();
private int addedPosition;
public Order(int quantity) {
this.quantity = quantity;
}
private double calculateProduct() {
double sum = 0;
for (int i = 0; i < positions.size(); i++) {
sum = positions.get(i).getPrice();
}
return sum;
}
double sumOrder() {
double sum = 0;
for (Position x : positions) {
sum += calculateProduct();
}
return sum;
}
void addPosition(Position p) {
if (!positions.contains(p)) {
positions.add(p);
} else {
quantity++;
}
}
void deletePosition(int index) {
positions.remove(index);
}
public String toString() {
System.out.println("Order is: ");
for (Position p : positions) {
System.out.println(positions.toString());
}
return "Order sum is: " + sumOrder();
}
}
You already are overriding toString method in Position class so you just need to call that toString method on the position object when iterating the position objects from inside your Order class' toString() method.
And as #Federico points out in the comments you shouldn't System.out.println from toString methods. Just append to a string the details you require displaying and return that string.
You can achieve your desired result like so:
public class Position {
.
.
#Override
public String toString() {
return String.format("%4s,%4s\n", name, price);
}
}
public class Order {
.
.
#Override
public String toString() {
StringBuilder sb = new StringBuilder("Order details: \n");
sb.append("Quantity: ").append(quantity).append("\n");
for (Position p : positions) {
sb.append(p);
}
sb.append("Order sum is: ").append(sumOrder());
return sb.toString();
}
}
I am quite new to the concepts of Java. I have designed a shopping cart application using core java. But i am not able to get the desired output.
Here is my pojo class item.java
package com.shop.data.*;
public class Item
{
private int Itemid;
private String category;
private String name;
private double price;
private String size;
/**
* #return the category
*/
public String getCategory() {
return category;
}
public Item(int itemid) {
super();
Itemid = itemid;
}
/**
* #param category the category to set
*/
public void setCategory(String category) {
this.category = category;
}
// -------------------------------------------------------
// Create a new item with the given attributes.
// -------------------------------------------------------
public Item (String itemcategory ,String itemName, double itemPrice,String itemSize)
{
name = itemName;
price = itemPrice;
size = itemSize;
category = itemcategory;
}
public Item(String itemName, int itemPrice, String size) {
// TODO Auto-generated constructor stub
}
/**
* #return the size
*/
public String getSize() {
return size;
}
/**
* #param size the size to set
*/
public void setSize(String size) {
this.size = size;
}
// -------------------------------------------------
// Returns the unit price of the item
// -------------------------------------------------
public double getPrice()
{
return price;
}
// -------------------------------------------------
// Returns the name of the item
// -------------------------------------------------
public String getName()
{
return name;
}
/**
* #return the itemid
*/
public int getItemid() {
return Itemid;
}
/**
* #param itemid the itemid to set
*/
public void setItemid(int itemid) {
Itemid = itemid;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #param price the price to set
*/
public void setPrice(double price) {
this.price = price;
}
public String toString ()
{
return (name + "\t" + price + "\t"+ size + "\t");
}
}
The main class is ShopCartTest.java
package com.shop.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import com.shop.data.*;
public class ShoppingCartTest {
private static Scanner scan;
public static void main(String[] args) {
// *** declare and instantiate a variable cart to be an empty ArrayList
shopping();
}
public static void shopping() {
ArrayList<Item> ItemCart = new ArrayList<Item>();
Map<Item, Integer> Quantity = new HashMap<Item, Integer>();
Item item = null;
Inventory inventory = null;
String category = null;
String itemName;
String itemSize;
double itemPrice = 0;
double totalPrice = 0.0;
double sum = 0.0;
int itemquantity;
scan = new Scanner(System.in);
String keepShopping = "y";
System.out.println("****Shopping Cart****");
do {
System.out.println("Select Category: ");
category = scan.nextLine();
if (category.equals("men") || category.equals("Men")) {
System.out
.println("Available Items: \n1Shirt : 900 \n2.T-Shirt : 700 \n3.Jean: 1500.\n");
System.out.println("Select Item to Add to your Bag: ");
itemName = scan.nextLine();
if (itemName.equals("Shirt") || (itemName.equals("shirt"))) {
itemPrice = 900;
} else if (itemName.equals("T-Shirt")
|| (itemName.equals("t-shirt"))) {
itemPrice = 700;
} else
itemPrice = 1500;
} else {
System.out
.println("Available Items: \n1.Dress : 250 \n2.Top : 350 \n3.Jean: 1500.\n");
System.out.println("Select Item to Add to your Bag: ");
itemName = scan.nextLine();
// *** create a new item and add it to the cart
if (itemName.equals("Dress") || (itemName.equals("dress"))) {
itemPrice = 250;
} else if (itemName.equals("Top") || (itemName.equals("top"))) {
itemPrice = 350;
} else
itemPrice = 1500;
}
System.out.print("Available Sizes \nS \tM \tL: ");
itemSize = scan.nextLine();
System.out.print("Enter the quantity: ");
itemquantity = scan.nextInt();
item = new Item(category, itemName, itemPrice, itemSize);
ItemCart.add(item);
Quantity.put(item, itemquantity);
// *** print the contents of the cart object using println
for (int i = 0; i < ItemCart.size(); i++) {
Item itm = ItemCart.get(i);
System.out.println(itm);
}
// Print out the results
System.out.print("Continue shopping (y/n)? ");
scan.nextLine();
keepShopping = scan.nextLine();
} while (keepShopping.equals("y"));
for (int i = 0; i < ItemCart.size(); i++) {
Quantity.put(item, itemquantity);
Item itm = ItemCart.get(i);
System.out.println(itm);
totalPrice = itemquantity * itm.getPrice();
for (int j = 0; i < ItemCart.size(); i++)
sum += totalPrice;
}
System.out.println("The total price is: " + sum);
System.out.println("Do you wan to proceed to checkout (y/n): ");
if (scan.nextLine().equals("y")) {
System.out.println("Thank you for shopping with us!");
} else {
shopping();
}
}
}
There are 4 pojo's Cart, inventory,Item, User. The user must be able to select multiple items of multiple quanties. (For items a list is been created and for the quantity: map. where item object is the key and quantity is the value). The user slects category, item, then quatity. Then he can proceed to checkout. So when he decides to checkout. He must be able to see the various items purchased ie (itemName, SIxe ,UnitPrice, unitprice*quantity) and finally the Total Price.
How do i achieve this? I am kinda lost!
Some pointers:
You should use proper naming conventions (i.e. variables and methods name starts with a lower case letter)
ItemCart is redundant, you can remove it and use the keys of Quantity
a Map provides an entrySet method, using that on Quantity will help you list the items in the cart (keys) and compute the total price using the item (key) price and quantity (value)
I have two equals methods in code, yet neither of them work. I made one myself and then I also auto generated one from Eclipse via source. I've run the program multiple times with one or an other and again, neither work.
import java.util.Arrays;
import java.util.Scanner;
import java.math.*;
public class Item {
static //the properties of an Item
double cash=59;
static double sum=0;
private int priority;
private String name;
private double price;
//default constructer
public Item() {
priority = -1; //fill with default values
price = 0.0;
name = "No name yet";
}
public Item(int priority, String name, double price) {//constructor with all 3 arguments
this.priority = priority;
this.name = name;
this.price = price;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
//priority must be between 1 and 7
if (priority > 0 && priority <= 7) {
this.priority = priority;
} else {
//otherwise default to 0
System.err.println("Error, enter 1 through 7");
//this.priority = 0;
}
}
public String getName() {
return name;
}
public void setName(String name) {
//would I put equals method here. name.equals.name?
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
//price between 0 and 100 inclusive
if (price >= 0.00) {
if (price <= 100.00) {
this.price = price;
cash = cash-=price;
sum=sum+=price;
} else {
System.err.println("Error: price to high");
}
} else {
System.err.println("Error: price to low");
}
}
public boolean equals(Item otherItem){
if(this.getPriority()==otherItem.getPriority());
System.err.println("Error, Same Priorities detected");
return true;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + priority;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Item)) {
return false;
}
Item other = (Item) obj;
if (priority != other.priority) {
return false;
}
System.err.println("Error, Same Priorities detected");
return true;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Item [Price=").append(getPrice()).append(", ");
if (getName() != null) {
builder.append("Name=").append(getName()).append(", ");
}
builder.append("Priority=").append(getPriority()).append("]");
return builder.toString();
}
public static void main(String[] args) {
Item[] list = new Item[2];
Scanner keyboard = new Scanner(System.in);
for (int i = 1; i <= list.length; i++) {
if(cash==59)
{
System.out.println("You have 59 dollars");
}
Item anItem = new Item(); // new item object created 7 times
System.out.println("Enter an item you want to add to your list " + i);
anItem.setName(keyboard.next());
System.out.println("Enter a price " + i);
anItem.setPrice(keyboard.nextDouble());
System.out.println("Enter the priority of the item " + i);
anItem.setPriority(keyboard.nextInt());
list[i-1] = anItem;
System.out.println(Arrays.toString(list));
System.out.println("Cash left "+cash);
System.out.println("Sum of Items "+sum);
if(sum>59)
{System.out.println("Error, you ran out of money");
System.out.println(Arrays.toString(list));}
}
System.out.println( list[1].getPriority());
}
}
This method here is completely biting you in the a**
public boolean equals(Item otherItem){
if(this.getPriority()==otherItem.getPriority());
System.err.println("Error, Same Priorities detected");
return true;
}
First, there's an ; after the if's condition so it's not doing anything and therefore your method is always returning true.
Second, this method overloads the equals(Object) method that you should be overriding and using. Get rid of it.
When overriding methods, annotate them with #Override. With an IDE that will do a check and validate that you are actually trying to override a method.
I was create a book inventory program.
I has two classes one is the main class, and the other one is the constructor class name Item.
On the main class, i has create a array (Item[] book = new Item[100]) to store my input.
And in my Item class, i want to create a function below
public boolean addItem(Item[] iArray, String itemCode){
boolean c = false;
for(int i=0; i<iArray.length; i++){
if(iArray[i].getItemCode().equals(itemCode)){
c = true;
}
else{
c = false;
}
}
return c;
}
how to i make that Item[] iArray sync with the book array in main class?
public class Item {
private String itemCode;
private String description;
private int quantity;
private double costprice;
private double sellprice;
private String status = "Available";
private boolean check;
private double discount;
public Item(){
this("A000","default",0,0.00,0.00,0.25,"Available");
}
//construtor with parameter
public Item(String itemCode, String description, int quantity, double costprice, double sellprice, double discount, String status){
this.setItemCode(itemCode);
this.setDescription(description);
this.setQuantity(quantity);
this.setCostprice(costprice);
this.setSellprice(sellprice);
this.setStatus(status);
this.setDiscount(discount);
}
//setter and getter methods
public void setItemCode(String itemCode){
this.itemCode = itemCode;
}
public String getItemCode(){
return this.itemCode;
}
public void setDescription(String description){
this.description = description;
}
public String getDescription(){
return this.description;
}
public void setQuantity(int quantity){
this.quantity = quantity;
}
public int getQuantity(){
return this.quantity;
}
public void setCostprice(double costprice){
this.costprice = costprice;
}
public double getCostprice(){
return this.costprice;
}
public void setSellprice(double sellprice){
this.sellprice = sellprice;
}
public double getSellprice(){
return this.sellprice;
}
public void setStatus(String status){
this.status = status;
}
public String getStatus(){
return this.status;
}
public void setDiscount(double discount){
this.discount = discount;
}
public double getDiscount(){
return this.discount;
}
public void setCheck(boolean check){
this.check = check;
}
public boolean getCheck(){
return this.check;
}
public boolean addItem(Item[] iArray, String itemCode){
boolean c = false;
for(int i=0; i<iArray.length; i++){
if(iArray[i].getItemCode().equals(itemCode)){
c = true;
}
else{
c = false;
numberofobject++;
}
}
return c;
}
public void displaymenu(){
System.out.println("Menu");
System.out.println("1. Add New Item");
System.out.println("2. Search");
System.out.println("3. Edit Details");
System.out.println("4. Edit Quantity");
System.out.println("5. Stop Sell");
System.out.println("6. List");
System.out.println("7. Exit");
}*/
public String toString(){
String msg = "";
msg = this.getItemCode()+"\t\t\t\t"+this.getDescription()+"\t\t\t\t"+this.getQuantity()+"\t\t\t\t"+this.getCostprice()+"\t\t\t\t"+this.getSellprice()+"\t\t\t\t"+this.getDiscount()+"\t\t\t\t"+this.getStatus();
return msg;
}
this is my Item class.
import java.util.*;
public class Driver {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int choice,quantity,NOI=0;
double cprice,sprice,discount;
String itc,name,status = "Available";
boolean check = true;
Item[] book = new Item[100];
Scanner s1 = new Scanner(System.in);
do{
Item display = new Item();
display.displaymenu();
System.out.print("Please Select Menu: ");
choice = s1.nextInt();
if(choice==1){
do{
System.out.print("Please Enter the Item Code: ");
itc = s1.next();
//for(int i=0; i<book.length; i++){
//book[i].addItem(book, itc);
if(display.addItem(book, itc)==true){
System.out.println("the book item code already exist."+NOI);
check = false;
}
else
{
check = true;
} //This is the question where i faced.
//}
}while(check==false);
System.out.print("Please Enter the Description: ");
name = s1.next();
System.out.print("Please Enter the Quantity: ");
quantity = s1.nextInt();
System.out.print("Please Enter the Cost Price: ");
cprice = s1.nextDouble();
System.out.print("Please Enter the Sell Price: ");
sprice = s1.nextDouble();
System.out.print("Please Enter the Discount: ");
discount = s1.nextDouble();*/
book[NOI] = new Item(itc,name,quantity,cprice,sprice,discount,status);
NOI++;
}
when i add the second item, there was a error (Exception in thread "main" java.lang.NullPointerException),
how to solve it?
Your method does not do what you want, because even if you find the item code, the loop continues. You probably want something like this instead:
public boolean addItem(Item[] iArray, String itemCode){
for (Item item : iArray) {
if (item.getItemCode().equals(itemCode)) {
return true;
}
}
return false;
}
Note that the method you posted seems oddly named, because it does not add anything anywhere.
You might also consider using a List<Item> (ArrayList, etc.) instead of an Item[].
I am not sure I understand what you are looking for so if my answer is irrelevant just comment it and I will delete.
I assume you are trying to store information : add new item with its code to an array. But I'm not sure if you're:
trying to insure the uniqueness of your item in the array before inserting it:
maybe you can use a set of codes, it will simplify your problem, just check with .contains() and then add it or not
trying to add it to the list and if it already exist perform something (incrementation of the number of book for the code?)
maybe you can use a HashMap with code as key and book as item.
In your current state, your method addItem does not add anything, just return if your last book in the array matches your code...
I have an assignment where I have to create three classes, a client class that performs all I/O, a catalog class that maintains a list of catalogItem objects and a catalogItem class that defines a single item in the store's catalog.
I'm trying to start simple at first and create the array and make sure that it is accepting data before I move on to the rest of the assignment. I was able to compile it with no issues but when I am trying to display the array, I get nothing.
import java.util.Scanner;
public class lab3
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
Catalog catalog = new Catalog();
boolean endCatalog = false;
while (!endCatalog)
{
System.out.println("Please choose and option: \n"
+ "1 - Display all items of the catalog\n"
+ "2 - Display an item by keyword\n"
+ "3 - Add an item to the catalog\n"
+ "4 - Remove an item from the catalog\n"
+ "5 - Change the cost of one item in the catalog\n"
+ "6 - Change the cost of all items in catalog by percent\n"
+ "7 - Exit");
int choice = in.nextInt();
switch (choice) {
case 1: System.out.println(catalog.displayAll()); break;
case 2: System.out.println("Display keyword"); break;
case 3: System.out.println("Add item:\nEnter ID: ");
int newId=in.nextInt();
System.out.println("Enter description: ");
String newDesc=in.next();
System.out.println("Enter cost: ");
double newCost=in.nextDouble();
catalog.add(newId, newDesc, newCost); break;
case 4: System.out.println("Remove item"); break;
case 5: System.out.println("Change cost of one item"); break;
case 6: System.out.println("Change cost by %"); break;
case 7: endCatalog=true; break; }
}
}
}
class Catalog
{
final static int MAX = 100;
private CatalogItem[] catalogItems;
int inUse;
public Catalog()
{
catalogItems=new CatalogItem[MAX];
}
public void add(CatalogItem newItem)
{
inUse = 0;
if(inUse<MAX) {
catalogItems[inUse] = newItem;
inUse++; }
}
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
/*public void remove(int id)
{
}
public String find(String keyword)
{
}
public void changeCost(int id, double percent)
{
}
public void increaseCost(double percent)
{
}
public String toString()
{
}
public boolean equals(Catalog obj)
{
}*/
public String displayAll()
{
String str = "";
for (int i=0; i<inUse; i++) {
str = str + "\n" + catalogItems[i]; }
return str;
}
}
class CatalogItem
{
private int itemID;
private String description;
private double cost;
public CatalogItem()
{
itemID = 1;
description = " ";
cost = 0.0;
}
public CatalogItem(int newID, String newDesc, double newCost)
{
itemID = newID;
description = newDesc;
cost = newCost;
}
public int getItemID()
{
return itemID;
}
public void setItemID(int newID)
{
itemID=newID;
}
public String getDescription()
{
return description;
}
public void setDescription(String newDesc)
{
description=newDesc;
}
public double getCost()
{
return cost;
}
public void setCost(double newCost)
{
cost=newCost;
}
public String toString()
{
return itemID + ", " + description + ", " + cost;
}
public boolean equals(CatalogItem obj)
{
return false;
}
}
Here's the problem:
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
What happens to newItem after it is created?
You call this method to add the catalog item:
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
But as we can see, this doesn't actually do anything with the object it creates. Did you mean to have this overload of add() call the other one? That would be a good design.
Also, in the other version of add(), you do this:
inUse = 0;
Since you reset inUse every time add() is called, your array will never contain more than one item. Do you see why this is? You should just take this line out.
There is not items ever added to:
private CatalogItem[] catalogItems;
That is so, because you call only this method:
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
And that one will never call method that actually tries to add something to the array:
public void add(CatalogItem newItem)
{
inUse = 0;
if(inUse<MAX) {
catalogItems[inUse] = newItem;
inUse++; }
}
In the long run that method will also not work, because item is always added to the index 0. That is so, because as first thing you always set: inUse = 0.