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...
Related
I have an ArrayList that contains objects. Each of the object has 3 values: String name, double price, int quantity. How to write method that will sum all doubles of objects and print the result. And also if int quantity>1, price will be multiplied by quantity.
Code that i wrote so far:
Product class
public class Product {
private String name;
private double price;
private int quantity;
public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public static Product createProduct(String name, double price, int quantity){
return new Product(name, price, quantity);
}
}
Product list class
import java.util.ArrayList;
import java.util.List;
public class ProductList {
private String name;
List<Product> newList;
public ProductList(String name) {
this.name = name;
this.newList = new ArrayList<>();
}
public boolean addNewProduct(Product product) {
if (findProduct(product.getName()) >= 0) {
System.out.println("Product is already on the list");
return false;
}
newList.add(product);
return true;
}
public boolean removeProduct(Product product) {
if (findProduct(product.getName().toUpperCase()) < 0) {
System.out.println("Product not found");
return false;
}
newList.remove(product);
return true;
}
private int findProduct(String productName) {
for (int i = 0; i < newList.size(); i++) {
Product product = newList.get(i);
if (product.getName().equals(productName)) {
return i;
}
}
return -1;
}
public Product queryProduct(String name) {
int position = findProduct(name);
if (position >= 0) {
return this.newList.get(position);
}
return null;
}
public double sumProducts() {
double sum = 0;
for (int i = 0; i < newList.size(); i++) {
sum += newList.get(i).getPrice();
}
return sum;
}
/*public boolean listProducts(){};
public boolean updateProduct(){};
*/
}
Simulation class:
public class Simulation {
private static Scanner scanner = new Scanner(System.in);
private static ProductList myProductList = new ProductList("My list");
private static void addNewProduct() {
System.out.println("Enter new product name: ");
String name = scanner.nextLine();
System.out.println("Enter new product price: ");
double price = scanner.nextDouble();
System.out.println("Enter new product quantity");
int quantity = scanner.nextInt();
Product newProduct = Product.createProduct(name, price, quantity);
if (myProductList.addNewProduct(newProduct) == true) {
System.out.println("New product added: " + name + " | price: " + price + " | quantity: " + quantity);
}
}
private static void removeProduct() {
System.out.println("Enter product name: ");
String name = scanner.nextLine().toUpperCase();
Product existingProduct = myProductList.queryProduct(name);
if (existingProduct == null) {
System.out.println("No such product");
return;
}
if (myProductList.removeProduct(existingProduct)) {
System.out.println("Sucessfully deleted product: " + existingProduct.getName());
} else {
System.out.println("Error deleting");
}
}
private static void printActions() {
System.out.println("Avaiable actions");
System.out.println("press: ");
System.out.println("0 - to shut down\n" +
"1 - to add new product\n" +
"2 - to remove product\n" +
"3 - to sum all products");
}
private static void sumProducts(){
myProductList.sumProducts();
}
public static void main(String[] args) {
printActions();
boolean quit = false;
while (!quit)
try {
System.out.println("\nEnter action: ");
int action = scanner.nextInt();
scanner.nextLine();
switch ((action)) {
case 0:
System.out.println("\nShutting down...");
quit = true;
break;
case 1:
addNewProduct();
break;
case 2:
removeProduct();
break;
}
} catch (InputMismatchException e) {
System.out.println("Bad key pressed, only values form 0 to 2 accepted");
scanner.nextLine();
}
}
}
Thanks in advance
You can do it in one line using Java 8.
public double sumProducts() {
return newList.stream().mapToDouble(product -> product.getPrice() * product.getQuantity()).sum();
}
If you use double to store the price, you will get incorrect answers when you try to add and multiply the values. For example, 0.1 + 0.2 is NOT the same double as 0.3. If you want accurate arithmetic for decimal numbers, you should use the BigDecimal class in place of double. If you don't do that, I can guarantee that your program will sometimes give wrong answers.
So you need to change your Product class as follows.
public class Product {
private String name;
private BigDecimal price;
private int quantity;
public Product(String name, BigDecimal price, int quantity) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public BigDecimal getPrice() {
return price;
}
public static Product createProduct(String name, BigDecimal price, int quantity){
return new Product(name, price, quantity);
}
}
You will also need to make corresponding changes in the code that calls the methods of this class.
Once you've done that, you can use the methods of the BigDecimal class to do arithmetic. It might look something like this.
public BigDecimal calculateTotalPrice() {
BigDecimal total = BigDecimal.ZERO;
for (Product product : newList) {
BigDecimal linePrice = product.getPrice().multiply(new BigDecimal(product.getQuantity()));
total = total.add(linePrice);
}
return total;
}
the sum of each product was missing multiply by its quantity.
public double sumProducts() {
double sum = 0;
for (int i = 0; i < newList.size(); i++) {
Product product = newList.get(i);
sum += product.getPrice() * product.getQuantity();
}
return sum;
}
I'm learning java and my programming skills are are good. I have been asked to find out the problem with codes below. when I paste them on netbeans, the error that had been detected was in the public class CheckoutProgram (String wordIn = Keyboard.readInput(); and wordIn = Keyboard.readInput();) and I noticed that the public static void method was empty but I'm not sure it has anything to do with the error. I have tried to find a solution myself but I can't sort it out. Can you help me with this issue? please
import java.io.*;
import java.text.DecimalFormat;
public class CheckoutProgram {
public static void main (String[] args) {
}
public void start() {
SalesItem[] items = getStock();
System.out.print("Type item code (press enter to finish):");
String wordIn = Keyboard.readInput();
SalesItem[] goods = new SalesItem[1000];
int count = 0;
while (wordIn.length()>=4 && wordIn.length()<=4){
for (int i=0;i<items.length;i++) {
if (items[i] != null && wordIn.equals(items[i].getItemCode())){
System.out.println(items[i]);
goods[count] = items[i];
}
}
System.out.print("Type item code (press enter to finish):");
wordIn = Keyboard.readInput();
count++;
}
System.out.println();
System.out.println("==========Bill==========");
double amountDue = 0.0;
for (int i=0; i<count; i++){
System.out.println(goods[i]);
amountDue = amountDue + goods[i].getUnitPrice();
}
System.out.println();
System.out.println("Amount due: $" + new DecimalFormat().format(amountDue));
System.out.println("Thanks for shopping with us!");
}
// method to read in "stock.txt" and store the items for sale in an array of type SalesItem
private SalesItem[] getStock(){
SalesItem[] items = new SalesItem[1000];
try {
BufferedReader br = new BufferedReader(new FileReader("stock.txt"));
String theLine;
int count = 0;
while ((theLine = br.readLine()) != null) {
String[] parts = theLine.split(",");
items[count] = new SalesItem(parts[0],parts[1],Double.parseDouble(parts[2]));
if (parts.length==4){
String discount = parts[3];
String numPurchases = discount.substring(0, discount.indexOf("#"));
String price = discount.substring(discount.indexOf("#")+1);
items[count].setNumPurchases(Integer.parseInt(numPurchases));
items[count].setDiscountedPrice(Double.parseDouble(price));
}
count++;
}
}
catch (IOException e) {
System.err.println("Error: " + e);
}
return items;
}
}
import java.text.DecimalFormat;
public class SalesItem {
private String itemCode; //the item code
private String description; // the item description
private double unitPrice; // the item unit price
// An item may offer a discount for multiple purchases
private int numPurchases; //the number of purchases required for receiving the discount
private double discountedPrice; // the discounted price of multiple purchases
// the constructor of the SalesItem class
public SalesItem (String itemCode, String description, double unitPrice){
this.itemCode = itemCode;
this.description = description;
this.unitPrice = unitPrice;
}
// accessor and mutator methods
public String getItemCode(){
return itemCode;
}
public void setItemCode(String itemCode){
this.itemCode = itemCode;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
public double getUnitPrice(){
return unitPrice;
}
public void setUnitPrice(double unitPrice){
this.unitPrice = unitPrice;
}
public int getNumPurchases(){
return numPurchases;
}
public void setNumPurchases(int numPurchases){
this.numPurchases = numPurchases;
}
public double getDiscountedPrice(){
return discountedPrice;
}
public void setDiscountedPrice(double discountedPrice){
this.discountedPrice = discountedPrice;
}
// the string representation of a SalesItem object
public String toString(){
return description + "/$" + new DecimalFormat().format(unitPrice);
}
}
Keyboard most likely doesn't exist. It isn't a part of the standard Java library. You would have to import a class that uses Keyboard if you are trying to use some custom class to read user input.
I assume you are getting the error because you do not have the class Keyboard. Check for a file called Keyboard.java.. This is more of a comment than an answer.
Firstly you are using public for a class CheckoutProgram so the file name should be same as the class name when you used public access specifier for a class.
Secondly the Keyboard class is missing in your program so please check with these issues.
I am relatively new to java and learning to program, this being my 8th week at uni. I have been fiddling around with my code for the past day and I have been searching for the past hour or two for a similar question that could help answer my problem but have not found one that helps my particular situation, at least not that I could understand.
For an assignment, I have been asked to write a program with 3 classes(an interface, a store and a product class) and I have been going ok until I need to display data on the interface that is held in the product class. At the moment the code will compile fine but when I run the program and try to use the writeOutput() method I get a stack overflow error. Anyway this is what I have so far:
This is the method I am trying to get to work in the interface class:
private void writeOutput()
{
int productChoice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1),(2),(3)");
productChoice = console.nextInt();
System.out.println("The records of product " +productChoice+ " are:");
System.out.println("Name: "+matesStore.getName());
And this is one of the methods from the store class:
public String getName()
{
return getName();
}
Finally I'll include the getter and setter from the product class just in case:
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
Hopefully this is enough information for someone to be able to help me but if it is not, I am happy to upload all three classes in their entirety.
Cheers Cale.
Edit: I have decided to add all three classes to help people who wish to help me (just keep in mind that I am nowhere near finishing and my code is probably riddled with problems) Hopefully it's not too messy for you guys to understand. And sorry for not writing many comments, it's something i need to work on :)
import java.util.*;
public class MatesInterface
{
Store matesStore = new Store();
private void run()
{
showInterface();
chooseOption();
}
private void showInterface()
{
System.out.println("What would you like to do?:");
System.out.println("(1)Input data for the product");
System.out.println("(2)Show data from one product");
System.out.println("(3)Show the replenishment strategy for a product");
System.out.println("(0)Exit the program");
}
private void chooseOption()
{
int option;
boolean flag = false;
Scanner console = new Scanner(System.in);
System.out.print("Please choose an option: ");
option = console.nextInt();
if(option==1)
{
readInput();
}
else if(option==2)
{
writeOutput();
}
else if (option==3)
{
}
else if(option==0)
{
}
else
{
flag = true;
}
while (flag)
{
System.out.println("That is not a valid option.");
System.out.println("Please choose an option: ");
option = console.nextInt();
flag = false;
}
}
private void readInput()
{
Store matesStore = new Store();
String name;
int productChoice, demandRate;
double setupCost, unitCost, inventoryCost, sellingPrice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1), (2) or (3): ");
productChoice = console.nextInt();
System.out.println("Please enter the product's name: ");
name = console.next();
System.out.println("Please enter the product's demand rate: ");
demandRate = console.nextInt();
System.out.println("Please enter the product's setup cost: ");
setupCost = console.nextDouble();
System.out.println("Please enter the product's unit cost: ");
unitCost = console.nextDouble();
System.out.println("Please enter the product's inventory cost: ");
inventoryCost = console.nextDouble();
System.out.println("Please enter the product's selling price: ");
sellingPrice = console.nextDouble();
matesStore.addData(productChoice, name, demandRate, setupCost, unitCost, inventoryCost, sellingPrice);
chooseOption();
}
private void writeOutput()
{
int productChoice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1),(2),(3)");
productChoice = console.nextInt();
System.out.println("The records of product " +productChoice+ " are:");
System.out.println("Name: "+matesStore.getName());
}
public static void main (String[] args)
{
MatesInterface intFace = new MatesInterface();
intFace.run();
}
}
public class Store
{
// instance variables - replace the example below with your own
private Product product1, product2, product3;
public Store()
{
product1 = new Product();
product2 = new Product();
product3 = new Product();
}
public void addData(int option, String newName, int newDemand, double newSetup, double newUnit, double newInventory, double newPrice)
{
if (option==1) setData(product1, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
else if (option==2) setData(product2, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
else setData(product3, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
}
private void setData(Product product, String name, int demandRate, double setupCost, double unitCost, double inventoryCost, double sellingPrice)
{
product.setName(name);
product.setDemand(demandRate);
product.setSetup(setupCost);
product.setUnit(unitCost);
product.setInventory(inventoryCost);
product.setPrice(sellingPrice);
}
public String getName()
{
return getName();
}
}
import static java.lang.Math.*;
public class Product
{
private String name;
private int demandRate;
//private final int REPLENISHMENTRATE=0;
private double setupCost;
private double unitCost;
private double inventoryCost;
private double sellingPrice;
//Constructors for the class Product
public Product()
{
name = "No name yet.";
demandRate = 0;
unitCost = 0;
setupCost = 0;
inventoryCost = 0;
sellingPrice = 0;
}
public Product(String newName, int newDemand, double newSetup, double newUnit, double newInventory, double newPrice)
{
name = newName;
demandRate = newDemand;
unitCost = newUnit;
setupCost = newSetup;
inventoryCost = newInventory;
sellingPrice = newPrice;
}
// Accessor and mutator methods to access and modify data on a Product object
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
public void setDemand(int newDemand)
{
demandRate = newDemand;
}
public int getDemand()
{
return demandRate;
}
public void setUnit(double newUnit)
{
unitCost = newUnit;
}
public double getUnit()
{
return unitCost;
}
public void setSetup(double newSetup)
{
setupCost = newSetup;
}
public double getSetup()
{
return setupCost;
}
public void setInventory(double newInventory)
{
inventoryCost = newInventory;
}
public double getInventory()
{
return inventoryCost;
}
public void setPrice(double newPrice)
{
sellingPrice = newPrice;
}
public double getPrice()
{
return sellingPrice;
}
}
The method from the store class is recursivelly calling itself with no terminating clause, this is leading to StackOverflowError :
public String getName()
{
return getName(); // calls itself
}
Instead return the value of name variable if it exists in Store class, or whatever variable you want to be returned as a name:
public String getName()
{
// determine the product name you want
return myProduct.getName();
}
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.
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.