I need to be able to update the quantity very simply in this section of code:
import java.util.HashMap;
import java.util.Map;
public class StockData {
private static class Item {
Item(String n, double p, int q) {
name = n;
price = p;
quantity = q;
}
// get methods
public String getName() { return name; }
public double getPrice() { return price; }
public int getQuantity() { return quantity; }
// instance variables
private String name;
private double price;
private int quantity;
}
// with a Map you use put to insert a key, value pair
// and get(key) to retrieve the value associated with a key
// You don't need to understand how this works!
private static Map<String, Item> stock = new HashMap<String, Item>();
static {
// if you want to have extra stock items, put them in here
// use the same style - keys should be Strings
stock.put("00", new Item("Bath towel", 5.50, 10));
stock.put("11", new Item("Plebney light", 20.00, 5));
stock.put("22", new Item("Gorilla suit", 30.00, 7));
stock.put("33", new Item("Whizz games console", 50.00, 8));
stock.put("44", new Item("Oven", 200.00, 4));
}
public static String getName(String key) {
Item item = stock.get(key);
if (item == null) return null; // null means no such item
else return item.getName();
}
public static double getPrice(String key) {
Item item = stock.get(key);
if (item == null) return -1.0; // negative price means no such item
else return item.getPrice();
}
public static int getQuantity(String key) {
Item item = stock.get(key);
if (item == null) return -1; // negative quantity means no such item
else return item.getQuantity();
}
// update stock levels
// extra is +ve if adding stock
// extra is -ve if selling stock
public static void update(String key, int extra) {
Item item = stock.get(key);
if (item != null) item.quantity += extra;
}
}
I've built the GUI for the update page and just need the method to add into it?
Sorry for the trivial question but you have to start somewhere.
Thanks for your help.
I donĀ“t know if I really get your problem, but this is my suggestion to increase the quantity of your Item.
Just add a public method like this:
public void addQuantity(int q) { quantity += q }
I hope you meant this.
Add this method:
public void setQuantity(int q) { quantity = q }
And you may want to start reading at http://docs.oracle.com/javase/tutorial/
Related
I have an ArrayList< Item>, and I want to do a function that sum all the quantity of the items with same code, then display all the items with the quantity.
public class Item{
private String code;
private int quantity;
public Item(String InputCode, int InputQuantity)
{
this.code= InputCode;
this.quantity = InputQuantity;
}
}
Suppose i do the following
List<Item> items = new ArrayList<Item>();
items.add(new Item("A01", 1));
items.add(new Item("A02", 1));
items.add(new Item("B05", 2));
items.add(new Item("A01", 3));
items.add(new Item("Z02", 2));
items.add(new Item("A02", 2));
display();
then the desired output is
A01 4
A02 3
B05 2
Z02 2
I have no idea, can anyone give me some hints?
You can do this with streams:
import static java.util.stream.Collectors.*;
...
Map<String, Integer> map = items.stream()
.collect(groupingBy(Item::getCode,
summingInt(Item::getQuantity)));
Assuming your class has these getters:
public class Item {
...
public String getCode() {...}
public int getQuantity() {...}
}
This maps the item codes, A01, A02, etc. to the respective sums of their quantities.
You can get the output, sorted by the code, with:
map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEachOrdered((e) -> System.out.println(e.getKey() + " " + e.getValue()));
Note: Using .forEachOrdered(System.out::println) instead, produces output like A01=4, which is almost the same as the example you gave, and a little simpler than the above.
Create a map where string being the code and int will be quantity. Iterate over the list of item check if map contains the key if yes, add the quantity else add new key value pair.
Map<String, Integer> map = new Hashmap<String, Integer>();
for(Item item : items){
if(map.containsKey(item.code)){
int q = map.get(item.code) + item.quantity;
map.put(item.code, q);
} else {
map.put(item.code, item.quantity);
}
}
Here is an alternative using the Java 8 Stream API and a TreeMap:
The TreeMap by default keeps its keys sorted according to the comparable natural ordering.
Required imports
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.summingInt;
import java.util.TreeMap;
Sample code
Map<String, Integer> result = items.stream()
.collect(groupingBy(Item::getCode, TreeMap::new, summingInt(Item::getQtd)));
result.forEach((k, v) -> System.out.println(k + " " + v));
Output
A01 4
A02 3
B05 2
Z02 2
You can try something like this
Create a Map<String,Integer> countMap = new HashMap<>();
Iterate the list and add code as Key of a Map and quantity as Value.
Eg:
Map<String,Integer> countMap = new HashMap<>()
for(Item item: items){
Integer count=countMap.get(item.getCode())
// if null then add quantity and code
// eg: countMap.put(item.getCode(),item.getQuantity())
// if not null countMap.put(item.getCode(),count+item.getQuantity()
}
Check the stream framework and esp. the examples in the Collectors class. The "Compute sum of salaries by department" can be easily adopted to your problem.
Map<String, Integer> maps = new HashMap<String, Integer>();
Item item;
for (int i = 0; i < items.size(); i++) {
item = items.get(i);
maps.put(item.getCode(), maps.containsKey(item.getCode()) ? item.getQuantity()+ + maps.get(item.getCode()) : item.getQuantity());
}
item = null;
// Item Class
public class Item{
private String code;
private int quantity;
public Item(String InputCode, int InputQuantity)
{
this.code= InputCode;
this.quantity = InputQuantity;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
Just a solution from myside in java6. i have added getters and setters in your Item class and implements compraable on base of itemcode.
hope it may help you.
Modified Item Class.
public class Item implements Comparable<Item> {
private String code;
private int quantity;
public Item(String InputCode, int InputQuantity) {
this.code = InputCode;
this.quantity = InputQuantity;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
#Override
public int compareTo(Item o) {
// TODO Auto-generated method stub
return this.getCode().compareTo(o.getCode());
}
}
And method to get the desired list :
List<Item> getDesiredList(List<Item> itemList) {
List<Item> tempList = new ArrayList<Item>();
// sort list to maintain order
Collections.sort(itemList);
String itemCode = null;
int quantity = 0;
Item itemObj = null;
for (int i = 0; i < itemList.size(); i++) {
if (itemCode == null || itemCode.equals(itemList.get(i).getCode())) {
quantity = quantity + itemList.get(i).getQuantity();
} else {
itemObj = new Item(itemCode, quantity);
if (tempList.contains(itemObj)) {
tempList.remove(itemObj);
}
tempList.add(itemObj);
quantity = 0;
quantity = quantity + itemList.get(i).getQuantity();
}
itemCode = itemList.get(i).getCode();
if (i == itemList.size() - 1) {
itemObj = new Item(itemCode, quantity);
tempList.add(itemObj);
}
}
return tempList;
}
Hope it may help you.
I am working on invoice and have added jTable to my frame for multiple items, like I have 4 fields for user "item, quantity, rate, price" and user fills it all and click on add button then these fields are added to jTable with item id inlcuded.
now the problem I am facing when user enters the same item whereas that item is already added in the list and it duplicates the row in jTable.
All i want to update that row if the item is same, update its quantity field with adding new quantity value and price value.
i.e.
id |Item |qty| rate| Price|
--------------------------------------
12 |saee |3 | 300| 900 |
now if user enters the same item with 5 quantity, it should update same item or row with plus quantity and price like.
--------------------------------------
id |Item |qty| rate| Price|
--------------------------------------
12 |saee |8 | 300| 24000|
but instead of this, it adds a second row in jTable.
here is my code for adding items in to jTable
DefaultTableModel model = (DefaultTableModel) tbl_sale.getModel();
model.addRow(new Object[]{lbl_id.getText(), txt_item.getText(), txt_qty.getText(), txt_rate.getText(), txt_rs.getText()});
can anyone tell me what should i do?
Sometimes I think we forget that we're operating in an OO environment and the power that something like that can bring
What I mean is, you data can easily be encapsulated into an object, for example...
public class Order {
private int id;
private String item;
private int quanity;
private double unitPrice;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getQuanity() {
return quanity;
}
public void setQuanity(int quanity) {
this.quanity = quanity;
}
public double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public double getTotalPrice() {
return getUnitPrice() * getQuanity();
}
}
This also has the capacity to calculate the total price dynamically, rather than needing us to do it.
DefaultTableModel is good for representing disjointed pieces of information, but not so good at representing an object per row, to this end, I use an AbstractTableModel and customise it for the needs of the object, something like...
public class OrderTabelModel extends AbstractTableModel {
protected static final String COLUMN_NAMES[] = {"ID", "Item", "Qty", "Rate", "Price"};
protected static final Class COLUMN_TYPES[] = {int.class, String.class, int.class, double.class, double.class};
private List<Order> orders;
public OrderTabelModel() {
orders = new ArrayList<>(25);
}
public void add(Order order) {
orders.add(order);
fireTableRowsInserted(orders.size() - 1, orders.size() - 1);
}
public void remove(Order order) {
int row = orders.indexOf(order);
if (row >= 0) {
orders.remove(order);
fireTableRowsDeleted(row, row);
}
}
public void update(Order order) {
int row = orders.indexOf(order);
if (row >= 0) {
fireTableRowsUpdated(row, row);
}
}
public Order getOrderAt(int row) {
return orders.get(row);
}
#Override
public int getRowCount() {
return orders.size();
}
#Override
public int getColumnCount() {
return COLUMN_NAMES.length;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return COLUMN_TYPES[columnIndex];
}
#Override
public String getColumnName(int column) {
return COLUMN_NAMES[column];
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = null;
Order order = getOrderAt(rowIndex);
switch (columnIndex) {
case 0:
value = order.getId();
break;
case 1:
value = order.getItem();
break;
case 2:
value = order.getQuanity();
break;
case 3:
value = order.getUnitPrice();
break;
case 4:
value = order.getTotalPrice();
break;
}
return value;
}
}
Now, when you want to add/remove/update a given object, you can just call add/remove/update methods of the OrderTabelModel.
Be Sure though, when you want to update an Order, you're interacting with an instance from the model, otherwise things won't go as you expect...
OrderTableModel model = ...;
//...
Order order = model.getOrderAt(0);
order.setQuanity(10);
model.update(order);
I have an assignment to make this Restaurant Program. it Consists of an Order Class a product class and the main class. Order has an ArrayList to hold the products. I create an instance of the Order and then I add items through my main method.A product has a name(string) a bar-code(string), and a price(float).
Then I have to output a receipt.But what if a customer orders more of one product? Do I instantiate everything one by one? Is a second Beer Product independent? Should I hold quantities somehow? If I want to add a second beer I have to create a new product Beer2 etc? I don't know beforehand how many products each order will hold and the quantity of each so Is this way of instantiating proper? Thanks
Note: it is still incomplete as I want to deal with this before I move on.
import java.util.Date;
public class MyRestaurantTester {
public static void main(String[] args) {
Date currentDate = new Date();
Paraggelia order1 = new Paraggelia(currentDate,"11B");
Product Beer = new Product("Amstel","111222",1.20f);
Product Beef = new Product("Pork Beef","333444",8.50f);
order1.add(Beer);
order1.add(Beef);
System.out.println(order1.getReceipt(30f));
}
}
Order Class(nevermind the name Paraggelia I gave it)
import java.util.ArrayList;
import java.util.Date;
/*Notes to self:
* -Work on Comments
* -Javadocs maybe?
* -try to optimize the rough code.
*/
/*Order class*/
public class Paraggelia {
private Date orderDate;
private String tableNumber;
private int customerCount;
private ArrayList<Product> listOfItems;
/*Constructor(s)*/
Paraggelia(Date orderDate,String tableNumber){
this.orderDate=orderDate;
this.tableNumber=tableNumber;
this.listOfItems = new ArrayList<Product>();
}
/*Add && Delete Products from the Order class*/
public void add(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}else{
listOfItems.add(p);
}
}
public void delete(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}
else
{
listOfItems.remove(p);
}
}
/** Calculates and returns the total price
* Usually called directly as a parameter of getReceipt function
* */
public static float getTotalPrice(){
return 0;
}
/** Creates and returns the final Receipt!
* -Display must consist of:
* Item$ - BarCode# - Item Amount#
* Total Price#
* Table Number#
*/
public String getReceipt(float totalPrice){
StringBuilder receipt = new StringBuilder();
for(int i =0; i<this.listOfItems.size();i++){
receipt.append(listOfItems.get(i).getName());
receipt.append("\n");
}
return new String(receipt);
}
/*Getters && Setters */
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getTableNumber() {
return tableNumber;
}
public void setTableNumber(String tableNumber) {
this.tableNumber = tableNumber;
}
public int getCustomerCount() {
return customerCount;
}
public void setCustomerCount(int customerCount) {
this.customerCount = customerCount;
}
}
Product Class:
public class Product {
private String Name;
private String barCode;
private float sellingPrice;
/*Constructors: */
Product(){}
Product(String Name,String barCode,float sellingPrice){
this.Name=Name;
this.barCode=barCode;
this.sellingPrice=sellingPrice;
}
/*Getters & Setters*/
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
public float getSellingPrice() {
return sellingPrice;
}
public void setSellingPrice(float sellingPrice) {
this.sellingPrice = sellingPrice;
}
}
Instead of ArrayList ( List ) you can use Map ( HashMap for example )
MyRestaurantTester
public class MyRestaurantTester {
public static void main(String[] args) {
Date currentDate = new Date();
Paraggelia order1 = new Paraggelia(currentDate,"11B");
Product Beer = new Product("Amstel","111222",1.20f);
Product Beef = new Product("Pork Beef","333444",8.50f);
order1.add(Beer, 1);
order1.add(Beef, 5);
System.out.println(order1.getReceipt(30f));
}
}
Paraggelia
class Paraggelia {
private Date orderDate;
private String tableNumber;
private int customerCount;
private Map<Product, Integer> listOfItems;
/*Constructor(s)*/
Paraggelia(Date orderDate,String tableNumber){
this.orderDate=orderDate;
this.tableNumber=tableNumber;
this.listOfItems = new HashMap<Product, Integer>();
}
/*Add && Delete Products from the Order class*/
public void add(Product p, int quantity){
if(p == null)
{
throw new IllegalArgumentException();
}else{
listOfItems.put(p, quantity);
}
}
public void delete(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}
else
{
listOfItems.remove(p);
}
}
/** Calculates and returns the total price
* Usually called directly as a parameter of getReceipt function
* */
public static float getTotalPrice(){
return 0;
}
/** Creates and returns the final Receipt!
* -Display must consist of:
* Item$ - BarCode# - Item Amount#
* Total Price#
* Table Number#
*/
public String getReceipt(float totalPrice){
StringBuilder receipt = new StringBuilder();
for(Map.Entry<Product,Integer> entry : this.listOfItems.entrySet()) {
Product product = entry.getKey();
Integer quantity = entry.getValue();
receipt.append(product.getName() + " " + quantity);
receipt.append("\n");
}
return new String(receipt);
}
/*Getters && Setters */
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getTableNumber() {
return tableNumber;
}
public void setTableNumber(String tableNumber) {
this.tableNumber = tableNumber;
}
public int getCustomerCount() {
return customerCount;
}
public void setCustomerCount(int customerCount) {
this.customerCount = customerCount;
}
}
OUTPUT:
Pork Beef 5
Amstel 1
Three basic approaches come to mind:
Instantiate each product individually
Instead of ArrayList, have another structure that can associate items with quantities; or,
Make a class Article, which belongs to a Product: Product beerProduct = new Product("beer", "0129", 1.37); Article beer = new Article(beerProduct), beer2 = new Article(beerProduct).
The first solution gives you a lot of flexibility (e.g. to discount individual articles for, say, being damaged). The second solution is more economical with objects. The third one captures the intuition that all the Heineken bottles are the same. It is really up to what you want to do - both approaches are equally valid, for some purpose.
I've been working on my add method for a couple of hours now and seem to have hit a roadblock. My method is supposed to search through every node in the list to see if there is a matching employee number and if there isn't, add the object in order of employee number.
Unfortunately I cant even seem to add a node to the beginning or end of my list. I think I understand the logic. I have to search through my list for find where I want the node, then all I have to do is have the new node's link point the already existing one. I think that I'm either not creating the nodes properly or not linking them properly. Every time I try to test my code though, only one node appears in my list.
import java.util.*;
public class HumanResources
{
private EmployeeNode first;
employee data = new employee();
private class EmployeeNode
{
//data members of employeenode
private EmployeeNode link;
employee data = new employee();
private EmployeeNode()
{
data = null;
link = null;
}
private EmployeeNode (employee emp)
{
data = emp;
link = null;
}
}
public EmployeeNode search (employee search)
{
EmployeeNode current = first;
if (first == null)
{ return null;}
while((present != null) && (present.data != search))
{
present = present.link;
}
return present;
}
private EmployeeNode nextInList(EmployeeNode x)
{
return x.link;
}
public boolean isEmpty()
{
return ( first == null );
} // end of isEmpty()
public HumanResources()
{
first = null;
}
public HumanResources ( employee x)
{
this.data = x;
}
public boolean addEmployee( employee emp)
{
EmployeeNode current = new EmployeeNode();
current = first;
if (current == null)
{
first = new EmployeeNode(emp);
return true;
}
else
{
while(current.link != null)
{
EmployeeNode temp = new EmployeeNode();
temp.data = emp;
temp.link = current;
}
return true;
}
}
public Employee findEmployee(String EmpNumber)
{
EmployeeNode current = first;
if(first == null)
{
return null;
}
else{
while (current != null)
{
public String toString()
{
EmployeeNode display;
display = first;
String temp = "";
while(display != null)
{
temp += display.data + "\n";
display = display.link;
}
return temp;
}
}
And here is my employee class
import java.util.*;
/**
This class manipulate information relating to employees
*/
public class employee {
private String empNumber;
private String name;
private String department;
private double salary;
/**
Zero parameter constructor that sets the values to null
*/
public employee()
{
empNumber = null;
name = null;
department = null;
salary = 0.0;
}
/**
Four parameter constructor to initialize the data members to the give values
#param kempnumber Employee's ID number
#param kname Employee's name
#param kdepartment Employee's department name
#param ksalary Employee's salary
*/
public employee(String kempnumber, String kname, String kdepartment, double ksalary)
{
empNumber = kempnumber;
department=kdepartment ;
name = kname;
salary = ksalary;
}
/**
copy constructor
*/
public employee (employee copy)
{
empNumber = copy.empNumber;
name = copy.name;
department = copy.department;
salary = copy.salary;
}
/**
Four parameter constructor to set data members to given value
#param kname Employee's name
#param kdepartment Employee's department name
#param ksalary Employee's salary
*/
public void setEmployee(String kempnumber, String kname, String kdepartment, double ksalary)
{
empNumber = kempnumber;
department=kdepartment ;
name = kname;
salary = ksalary;
}
public String getEmpNumber() {
return empNumber;
}
public void setEmpNumber(String empNumber) {
this.empNumber = empNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary)
{
this.salary = salary;
}
public String toString()
{
return (empNumber + " " + name + " " + department + " " +salary);
}
public boolean equals(employee compareto) {
int firstemployee = Integer.parseInt(empNumber);
int secondemployee = Integer.parseInt(compareto.empNumber);
if (firstemployee == secondemployee) {
return true;
}
else {
return false;
}
}
public int compareTo(employee compareto)
{
int less = -1;
int same = 0;
int more = 1;
int firstemployee = Integer.parseInt(empNumber);
int secondemployee = Integer.parseInt(compareto.empNumber);
if(firstemployee > secondemployee)
{
return more;
}
else if(firstemployee == secondemployee)
{
return same;
}
else
{
return less;
}
}
}
For the addEmployee method, if you are adding to the front of the list you shouldn't need a while loop at all. Your 'first' variable is presumably maintaining a reference to the front of the loop, so all you need to do is create the employee, update the links and point 'first' towards it. Something like this...
public boolean addEmployee( employee emp){
if (first == null) {
first = new EmployeeNode(emp);
return true;
}
else { // first must != null
EmployeeNode temp = new EmployeeNode(emp); //create the new employee
temp.link = first; // link the new employee to the old employee at the front of the list
first = temp; //update the new front of list to be the new employee
return true;
}
}
Keep in mind though if you want to add it to the end of the list, you will need a while loop to search through the list and find the end before creating the new employee and updating the links.
If your getting confused with the links, try stepping through the code and drawing out the nodes with lines to represent the links to help get you used to visualising the linked list.
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.