Array is just printing out last element [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am having this error where it prints out just the last element entered, prints out it the same amount of times as there are elements that are supposed to be in the array.
I have tested it with a System.out.println and the elements that are being added appear to be correct. How do I fix this error?
package stock.control.system;
import java.util.*;
public class StockArrayList implements StockList {
private ArrayList<StockItem> StockItems;
private int index = 0;
private int update;
private int counter = 0;
public StockArrayList() {
StockItems = new ArrayList<StockItem>(counter);
}
#Override
public void addItem(StockItem item) {
StockItem aItem = new StockItem(StockItem.getItemID(),
StockItem.getItemDesc(),
StockItem.getPrice(),
StockItem.getQuantity(),
StockItem.getReOrderLevel());
StockItems.add(counter, aItem);
counter++;
}
#Override
public String formatStockList(){
String temp = StockItem.format();
for (StockItem items : StockItems) {
temp = temp + items.arrayFormat() + "\n";
}
return temp;
}
}
The main method:
public class StockArrayListTester {
public static void main(String[] args) {
StockArrayList Stock = new StockArrayList();
Stock.addItem(new StockItem("P123","1TB Hard drive",75.00,267,50));
Stock.addItem(new StockItem("P125","i7 6800HQ Processor",257.00,113,45));
Stock.addItem(new StockItem("P129","i5 500HQ Processor",127.00,10,45));
Stock.deleteItem("P129");
System.out.printf(Stock.formatStockList());
}
}
the stock item class
package stock.control.system;
import java.util.*;
public class StockItem {
private static String itemID; // Five alpha-numeric characters
private static String itemDesc; // Item description
private static double price; // Item price in pounds sterling
private static int quantity; // Quantity in stock
private static int reOrderLevel; // Level at which to re-order
public StockItem(String itemID, String itemDesc, double price, int quantity, int reOrderLevel) {
this.itemID = itemID;
this.itemDesc = itemDesc;
this.price = price;
this.quantity = quantity;
this.reOrderLevel = reOrderLevel;
}
#Override
public String toString() {
String toString ="[Item ID = " + this.itemID + ", Item Description = " +
this.itemDesc + ", Price = " + this.price + ", Quantity = " +
this.quantity + ", Re Order Level = " + this.reOrderLevel + "]";
return toString;
}
public static String format() {
String format = " STOCK ITEMS"
+ String.format("\n%-10s%-30s%-10s%-12s%-14s%-10s%-30s%-10s%-12s%-14s\n",
"ItemID","Item Description",
"Price","Quantity", "Re Order Level", "\n******",
" ****************"," *****", " ********",
" **************");
return format;
}
public String arrayFormat() {
return String.format("%-10s%-30s%-10s%-12s%-14s",
StockItem.getItemID(),
StockItem.getItemDesc(),
StockItem.getPrice(),
StockItem.getQuantity(),
StockItem.getReOrderLevel());
}
public static String getItemID(){
return itemID;
}
public static String getItemDesc() {
return itemDesc;
}
public static double getPrice() {
return price;
}
public double setPrice(double price) {
this.price = price;
return price;
}
public static int getQuantity() {
return quantity;
}
public int setQuantity(int quantity) {
this.quantity = quantity;
return quantity;
}
public static int getReOrderLevel(){
return reOrderLevel;
}
public int setReOrderLevel(int reOrderLevel){
this.reOrderLevel = reOrderLevel;
return reOrderLevel;
}
}
The output I get is:
STOCK ITEMS
ItemID Item Description Price Quantity Re Order
P129 i5 500HQ Processor 127.0 10 45
P129 i5 500HQ Processor 127.0 10 45
P129 i5 500HQ Processor 127.0 10 45
BUILD SUCCESSFUL (total time: 0 seconds)

As a rule, never set static fields in a constructor. It is almost certainly a bug. IMHO, this should be a compiler error but it's not.
In this case, you are expecting each instance of StockItem to be different, however by making the fields static you are ensuring there is only one copy, only one value for those fields. I suggest you make them instance fields.
public class StockItem {
private final String itemID; // Five alpha-numeric characters
private final String itemDesc; // Item description
private double price; // Item price in pounds sterling
private int quantity; // Quantity in stock
private int reOrderLevel; // Level at which to re-order
public StockItem(String itemID, String itemDesc, double price, int quantity, int reOrderLevel) {
this.itemID = itemID;
this.itemDesc = itemDesc;
this.price = price;
this.quantity = quantity;
this.reOrderLevel = reOrderLevel;
}

It's been a little while since I've used Java but it seems weird that in your addItem() method in your StockList class that you pass in a parameter 'item' but then never use it inside the method.
Why are you trying to "get" all of the properties of the stock item to add when you are passing them in to the function as a StockItem object?

Guess something is wrong here:
#Override
public void addItem(StockItem item) {
StockItem aItem = new StockItem(StockItem.getItemID(),
StockItem.getItemDesc(), StockItem.getPrice(), StockItem.getQuantity(), StockItem.getReOrderLevel());
StockItems.add(counter, aItem);
counter++;
}
All those getters are static methods. It does not make sense to me since I would think you want to get instance variables belonging to different objects. You must have initialiazed the StockItem class instance variables with the values printed out, otherwise I do not think your code would even compile.
Anyway why not adding the item passed as a parameter directly to the stock list?
Like so:
#Override
public void addItem(StockItem item) {
StockItems.add(counter, item);
counter++;
}

Related

How to display all information in toString

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();
}
}

Short Project: Electronics Inventory

I'm doing my short project that acts as a type of electronic store inventory. Here's the list of item's number, description, quantity, and price from the text file:
65321,Tablet,54,150.00
91524,Monitors,24,125.50
25013,Printers,30,65.75
32841,Router,67,90.15
53214,Modem,50,50.50
26442,Hard Drive,14,40.89
30224,Power Supplies,44,125.44
41557,CPU,39,149.54
71561,Headphones,40,75.24
This is what I've done so far:
InventoryCalculate.java
ArrayList<BookItem> inventory = new ArrayList<>();
BufferedReader inFile = new BufferedReader(new FileReader("C:\\Users\\Documents\\Data\\stock.txt"));
String line;
line = input.nextLine();
String[] tokens = line.split(",");
int itemNumber = Integer.parseInt(tokens[0]);
String description = tokens[1];
int quantity = Integer.parseInt(tokens[2]);
double unitCost = Double.parseDouble(tokens[3]);
System.out.println("Inventory Item");
System.out.println("Number Description Quantity Unit Price Value");
Inventorystock.java
public class InventoryItem {
private int itemNumber;
private String description;
private int quantity;
private double unitCost;
public InventoryItem(int itemNumber, String description, int quantity, double unitCost) {
this.itemNumber = itemNumber;
this.description = description;
this.quantity = quantity;
this.unitCost = unitCost;
}
public int getItemNumber() {
return itemNumber;
}
public void setItemNumber(int itemNumber) {
this.itemNumber = itemNumber;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getUnitCost() {
return unitCost;
}
public void setUnitCost(double unitCost) {
this.unitCost = unitCost;
} }
I'm having trouble figuring out how to get the total value of each item. Here what I need to see the result look like this
Expected output:
Number Description Quantity Unit Price Value
65321 Tablets 54 150.00 8,100.00
91524 Monitors 24 125.50 3,012.00
25013 Printers 30 65.75 1,972.50
32841 Routers 67 90.15 6,040.05
53214 Modems 50 50.50 2,525.00
26442 Hard Drives 14 40.89 572.46
30224 Power Supplies 44 125.44 5,519.36
41557 CPU 39 149.54 5,832.06
71561 Headphones 40 75.24 3,009.60
Create a method that takes the total quantity of the item, multiplies it by the unit cost and then returns the result. Add the following code to your InventoryItem class.
public double getTotalValueOfItem()
{
return unitCost * quantity;
}
Add another property in InventoryItem class as totalValue and add setter, getter methods with your logic. The best way to keep total value calculation in the method that you're displaying details.
public class InventoryItem {
private int itemNumber;
private String description;
private int quantity;
private double unitCost;
private double totalValue;
public InventoryItem(int itemNumber, String description, int quantity, double unitCost) {
this.itemNumber = itemNumber;
this.description = description;
this.quantity = quantity;
this.unitCost = unitCost;
}
public int getItemNumber() {
return itemNumber;
}
public void setItemNumber(int itemNumber) {
this.itemNumber = itemNumber;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getUnitCost() {
return unitCost;
}
public void setUnitCost(double unitCost) {
this.unitCost = unitCost;
}
public double getTotalValue() {
return totalValue;
}
public void setTotalValue(int quantity, double unitCost) {
this.totalValue = (double) quantity * unitCost;
}
}
You can add this method to print the item details
public void printDetails() {
System.out.println("Number\tDescription\tQuantity\tUnit Price\tValue");
List < InventoryItem > inventoryItemsList = new ArrayList < InventoryItem > ();
inventoryItemsList.add(new InventoryItem(1, "description 1", 2, 50.0));
inventoryItemsList.add(new InventoryItem(2, "description 2", 3, 40.0));
for (InventoryItem item: inventoryItemsList) {
System.out.println(item.itemNumber + "\t" + item.description + "\t" + item.quantity + "\t" + item.unitCost + "\t" + item.totalValue);
}
}
You can store the details of inventory items as a String or as a List as demonstrated in printDetails method. Hope this "printDetails" method solved your issue. If you really want to store item details as a string then you can store all item details into a string array.
Make sure to import required libraries and model classes in following way.
import java.util.List;
import java.util.ArrayList;
import <package>.InventoryItem;

Get methods in my subclass are getting errors and i cannot solve them

Here is the primary class (I am trying to build a program to check items in a stock):
/**
* Shows various details of an item.
*
* #author Brian Clarke
* #version 28 sept 2017
*/
public class Item {
// instance variables
private String id;
private String descr;
private int quantity;
private double price;
private double discount;
/**
* Constructor for objects of class Item
*/
public Item(String id, String descr, int quantity, double price, double discount) {
// initialise instance variables
id = id;
descr = descr;
quantity = quantity;
price = price;
discount = discount;
}
/**
* Get and set methods for variables.
*
*
*
*/
public String getid(String id) {
return id;
}
public String getdescr(String descr) {
return descr;
}
public int getquantity(int quantity) {
return quantity;
}
public double getprice(double price) {
return price;
}
public double getdiscount(double discount) {
return discount;
}
public void setid(String id) {
this.id = id;
}
public void setdescr(String descr) {
this.descr = descr;
}
public void setquantity(int quantity) {
if (quantity < 0)
quantity = 0;
this.quantity = quantity;
}
public void setprice(double price) {
if (price < 0)
price = 0.0;
this.price = price;
}
public void setdiscount(double discount) {
if (discount < 0 || discount > 0.8)
discount = 0;
this.discount = discount;
}
public String toString() {
return "Item1{" + "ID = " + id + ", description = " + descr + ", quantity = " + quantity + ", price = " + price + ", discount = " + discount + '}';
}
public double computeCost() {
return (quantity * price - quantity * price * discount); // Normal price minus price by the percentage discount should give the correct discounted price
}
}
And here is the test class where I am getting the errors in the last 5 lines, e.g ( method getid in class Item cannot be applied to given types; required: java.lang.String found: no arguments reason: actual and formal argument lists differ in length).
I am not sure how to fix them and have tried editing:
/**
* Test the class Item
* The code tests all methods in the class Item
* #author Brian Clarke
* #version 28 Sep 2017
*/
public class ItemTest {
public static void main(String[] args) {
// Create two objects to represent two stock items
Item item1 = new Item("ZA423", "Refurbished smartphone", 14, 149.99, 0.3);
Item item2 = new Item("BD015", "New 40' TV", 8, 299.99, 0.8);
item1.computeCost();
item2.computeCost();
item1.setid("ZA423");
item1.setdescr("Refurbished smarthphone");
item1.setquantity(14);
item1.setprice(149.99);
item1.setdiscount(0.3);
System.out.println(item1.toString());
item2.setid("BD015");
item2.setdescr("New 40' TV");
item2.setquantity(8);
item2.setprice(299.99);
item2.setdiscount(0.8);
System.out.printf("\nItem2 ID is: %s\n", item2.getid());
System.out.printf("\nItem2 Description is: %s\n", item2.getdescr());
System.out.printf("\nQuantity is: %s\n", item2.getquantity());
System.out.printf("\nPrice is: %f\n", item2.getprice());
System.out.printf("\nDiscount is: %f\n", item2.getdiscount());
}
}
The code is not complete but this is most of it. I've searched a lot but couldn't find any answers. I am very new to Java and any help would be appreciated.
You have defined getter methods incorrectly. In your implementation you expect to pass a parameter to each getter method, which does not make much sense, since getter method is meant to return a value. Instead
public String getid(String id) {
return id;
}
you should do:
public String getid() {
return id;
}
Remove all parameters from getter methods and it will work.
UPDATE:
Two Three more things worth mentioning:
constructor of Item class is incorrect. Assignments like id = id; won't work, you should do this.id = id; instead (you have to explicitly say that the id on the left side is a field in the class and id on the right side is a value passed as a constructor parameter)
when you use a constructor that expects all fields to be passed you can mark all fields as final and remove setter methods to prevent an instance of this class from changing its state - this is a good rule worth following
consider using camel-case notation. If your field name is id then getter method should be called getId and setter - setId. This is a convention widely used in Java programs.
You don't want to enter a parameter to getters method because you need to get the Id not set it to a new value otherwise you will get the same value you entered, and which in your case you didn't enter, that's why you're getting the error (missing parameter). Write this code instead so you can get the data you already set before:
/**
* Shows various details of an item.
*
* #author Brian Clarke
* #version 28 sept 2017
*/
public class Item {
// instance variables
private String id;
private String descr;
private int quantity;
private double price;
private double discount;
/**
* Constructor for objects of class Item
*/
public Item(String id, String descr, int quantity, double price, double discount) {
// initialise instance variables
id = id;
descr = descr;
quantity = quantity;
price = price;
discount = discount;
}
/**
* Get and set methods for variables.
*
*
*
*/
public String getid() {
return id;
}
public String getdescr() {
return descr;
}
public int getquantity() {
return quantity;
}
public double getprice() {
return price;
}
public double getdiscount() {
return discount;
}
public void setid(String id) {
this.id = id;
}
public void setdescr(String descr) {
this.descr = descr;
}
public void setquantity(int quantity) {
if (quantity < 0)
quantity = 0;
this.quantity = quantity;
}
public void setprice(double price) {
if (price < 0)
price = 0.0;
this.price = price;
}
public void setdiscount(double discount) {
if (discount < 0 || discount > 0.8)
discount = 0;
this.discount = discount;
}
public String toString() {
return "Item1{" + "ID = " + id + ", description = " + descr + ", quantity = " + quantity + ", price = " + price + ", discount = " + discount + '}';
}
public double computeCost() {
return (quantity * price - quantity * price * discount); // Normal price minus price by the percentage discount should give the correct discounted price
}
}

How to declare and addItem to ArrayList [closed]

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 6 years ago.
Improve this question
Build the ShoppingCart class with the following specifications. Note: Some can be method stubs (empty methods) initially, to be completed in later steps.
Private fields
String customerName - Initialized in ddefault constructor to "none"
String currentDate - Initialized in ddefault constructor to "January 1, 2016"
ArrayList cartItems
Default constructor
Parameterized constructor which takes the customer name and date as parameters (1 pt)
Public member methods
getCustomerName () accessor (1 pt)
getDate () accessor (1 pt)
addItem ()
Adds an item to cartItems array. Has parameter ItemToPurchase. Does not return anything.
...
ok so i got lost around the arrayList cartItems. I am not sure if I should declare it as a String or an int. Also not sure if how I declared it was correct or the way the asked it to be done. I also created a class called ItemToPurchase that goes with this and I need to create a class called ShoppingCartManager that has the main method. Here's what I have so far (I took some things out of the ShoppingCart class.)
ItemToPurchase.java
public class ItemToPurchase {
private String itemName;
private String itemDescription;
private int itemPrice;
private int itemQuantity;
public ItemToPurchase() {
itemName = "none";
itemPrice = 0;
itemQuantity = 0;
itemDescription = "none";
}
public void setDescription(String description) {
itemDescription = description;
}
public String getDescription() {
return itemDescription;
}
public String printItemCost() {
String str = getName() + " " + getQuantity() + " " + getPrice() + " " + (getQuantity() * getPrice());
return str;
}
public String printItemDescription() {
String k = getName() + " " + getDescription();
return k;
}
public void setName(String name) {
itemName = name;
}
public String getName() {
return itemName;
}
public void setPrice(int price) {
itemPrice = price;
}
public int getPrice() {
return itemPrice;
}
public void setQuantity(int quantity) {
itemQuantity = quantity;
}
public int getQuantity() {
return itemQuantity;
}
}
ShoppingCart.java
import java.util.ArrayList;
public class ShoppingCart {
Scanner sc = new Scanner(System.in);
private String customerName;
private String currentDate;
private ArrayList<String> cartItems = new ArrayList<String>();
public ShoppingCart(String customerName, String currentDate) {
customerName = "none";
currentDate = "January 1, 2016";
}
public void getCustomerName() {
}
public void getDate() {
}
public void addItem(String itemName) {
cartItems.add(itemName);
}
}
It seems to me your ArrayList does not need to hold ints or Strings, but rather ItemToPurchase instances. This would mean changing your ArrayList declaration to private ArrayList<ItemToPurchase> cartItems = new ArrayList<ItemToPurchase>(); This way you can add ItemToPurchase objects to the ArrayList, which I believe is what you are trying to do. Then change your addItem method in the ShoppingCart class to accept ItemToPurchase objects, instead of String objects.
public void addItem(ItemToPurchase item) {
cartItems.add(item);
}

Creating a invoiceline class

Invoice Line class represent some line in the invoice that records the item sold and the quantity.An invoice line should include the following attributes: item Sold: this is an instance variable of type Item.
quantity: an integer that represents the number of units being purchased of this item.Include the following methods in your Invoice Line class: A constructor that takes the following four input parameters: item number, item description, item price, and quantity. The constructor then uses the input parameters to initialize the two instance variables to getters and setters methods for the two instance variable so get Line Total: a method to calculate and return the total price for this line (i.e., quantity * item’s price). to String method that returns a one-line description of the invoice line. The description should include item’s details, quantity purchased, and total cost of the line.
*** I am trying to get the other variables from a different class called item class to the invoiceline class, but I cannot seem to do it. So far I have this. Any Help!?
public class InvoiceLine {
//Instance Variables
private Item itemSold;
private int quantity;
// Constructors
public InvoiceLine(){}
public InvoiceLine(String itemSold, int quantity){
itemSold = new Item(itemSold);
this.quantity = quantity;
}
//Getters
public Item getItemSold(){
return itemSold;
}
public int getQuantity(){
return quantity;
}
//Setters
private void setItemSold(Item itemSold){
this.itemSold = itemSold;
}
private void setQuantity(int quantity){
this.quantity = quantity;
}
// Methods
public double getLineTotal(double total){
total = itemPrice * quantity;
return total;
}
public String toString(){
String invoiceLine = "";
invoiceLine = (itemSold + " brought "+ quantity + ", which the total cost is "+ total);
return invoiceLine;
}
}
Item Class:
public class Item {
//Instance Variables
private int itemNum;
private String itemDescription;
private double itemPrice;
//Constructors
public Item(){}
//Initialize the three variables
public Item(int itemN, String itemDesc, double itemPri){
this.itemNum = itemN;
this.itemDescription = itemDesc;
this.itemPrice = itemPri;
}
public Item(String itemDesc){
this.itemDescription = itemDesc;
this.itemNum = 0;
this.itemPrice = 0;
}
//Getters
public int getItemNum(){
return itemNum;
}
public String getItemDescription(){
return itemDescription;
}
public double getItemPrice(){
return itemPrice;
}
//Setters
private void setItemNum(int itemN){
itemNum = itemN;
}
private void setItemDescription(String itemDesc){
itemDescription = itemDesc;
}
private void setItemPrice(double itemPri){
itemPrice = itemPri;
}
// toString method output description of the item
public String toString(){
String itemDetail = "";
itemDetail = ("Item number is "+ itemNum + ", which is a "+ itemDescription + " and price is " + itemPrice);
return itemDetail;
}
}
Try to change itemSold = new Item(itemSold); to this.itemSold = new Item(itemSold);
In this case the parameter itemSold is shadowing the attribute itemSold, so to access the attribute you have to prefix it with this.

Categories