Creating a Shoe object - java

I cannot figure out why my code does not register that there is a max size on the object. I maybe thought it was due to the fact that the bottom variables may override the Minimum and maximum values but, it does not seem to help
public class Shoes {
private static final int MIN_SIZE = 1;
private static final int MAX_SIZE = 15;
private String brand;
private double price;
private int size;
public Shoes(String brand, double price, int size) {
this.brand = brand;
this.price = price;
this.size = size;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if (price < 0) {
System.out.println("Price Must be greater than zero!\n");
return;
}
this.price = price;
}
public int getSize() {
return size;
}
public void setSize(int size) {
if (size > MAX_SIZE && size < MIN_SIZE) {
System.out.println("Invalid Size!\n");
}
}
#Override
public String toString() {
return "Shoe [brand = " + brand + ", price = " + price + ", size = " + size + "]";
}
public static void main(String[] args) {
Shoes myShoes = new Shoes("J.F.", 45.99, 10);
Shoes otherShoes = new Shoes("Addidas", 65.99, 16);
System.out.println("The shoes: ");
System.out.println(myShoes.toString());
System.out.println("Other Shoes: ");
System.out.println(otherShoes.toString());
}
}
The othershoes should register as an invalid size. however it just runs the code as normal and does not output the invalid size text at all I do not understand why.

As I see, in your constructor you are not using "setSize" method but you copy value from parameter directly to field "size". Because of that method "setSize" is not fired, so the validation in that method didn't happend. I suggest you modify the code of constructor, so instead of directly setting value of "size" field you would use "setSize" method like:
public Shoes(String brand, double price, int size) {
this.brand = brand;
this.price = price;
this.setSize(size);
}
Hope it helps!

Your issue is you're not checking the size in the constructor. You've relegated that to a separate method that is not called on object initialization.

You don't call the setSize method in your constructor. Thus, the check is not performed.
You can simply change the constructor to use the method like so:
public Shoes(String brand, double price, int size) {
this.brand = brand;
this.price = price;
setSize(size);
}

There are two problems.
1. The data validation you have in place inside the size setter doesn't work. Your current logic says that if size is greater than 15 AND (&&) less than 1, then it will register invalid. That condition will never be true. Rather, you should say greater than 15 OR (||) less than 1.
2. You're not ever calling the size setter with the validation. You should use the setters in your constructor. So your constructor would look like this:
public Shoes(String brand, double price, int size) {
setBrand(brand);
setPrice(price);
setSize(size);
}

Related

Retrieve specific value from Setter and Getter method inside Chaining methods using Java

I am trying to get specific value from setter method using java method chaining.
like if we do obj.setId(1).setValue(5).
how we can get value = 5 using obj.setId(1).getValue();
here is the main class
public class MenuDish {
private String name;
private double price;
private String description;
private int category;
private int spiciness;
private boolean healthy;
public MenuDish(){ //constrcutor
}
public MenuDish setPrice(double price){
if(price < 0.0){
this.price = 0.0;
}
else{
this.price = price;
}
return this;
}
public double getPrice() {
return this.price;
}
public MenuDish setDay(int day){
return new MenuDish();//just do nothing
}
}
Sub class
AdjustableMenuDish Class
public class AdjustableMenuDish extends MenuDish {
private int day;
private double price;
public AdjustableMenuDish(){ //constructor
setName(null);
setPrice(0);
setDescription(null);
setCategory(0);
setHealthy(false);
setSpiciness(0);
}
#Override
public MenuDish setDay(int day){
this.day = day;
return this;
}
}
Inside main method I am trying to do something like this.
AdjustableMenuDish dish = new AdjustableMenuDish();
dish.setDay(0).setPrice(3.4);
dish.setDay(3).setPrice(7.4);
System.out.println(dish.setDay(0).getPrice());//--->output 7.4 but how to
get 3.4 instead of 7.4
Basically I am trying to get specific price from day.
Edit
I want to pass Junit test case which is given below
#Test public void test_daily_prices() {
AdjustableMenuDish dish = new AdjustableMenuDish();
for (int i = MenuDish.MONDAY; i <= MenuDish.SUNDAY; i++) {
double p = 1.0+i;
double a = dish.setDay(i).setPrice(p).getPrice();
assertEquals(p, a, 0.0001);
}
for (int i = MenuDish.MONDAY; i <= MenuDish.SUNDAY; i++) {
double p = 1.0+i;
double a = dish.setDay(i).getPrice();
assertEquals(p, a, 0.0001);
}
}
Fail expected 1.0 but was 7.0
You need to pair days and prices together, rather than have them as single attributes of MenuDish. You could try something like:
class AdjustableMenuDish {
private double[] prices = new double[7]; // Assumes day as [0..6]
...
public AdjustableMenuDish setPrice(int day, double price) {
prices[day] = price;
return this;
}
public double getPrice(int day) {
return prices[day];
}
}
If every dish has a different price depending on the day, then this code could be in MenuDish. If it's only some dishes, then it probably belongs on AdjustableMenuDish.
Given that a price is really a price per day, I think you should submit the two together, ie. in one method (as above). If you really want to stick to your MenuDish API as it is now, then you could try something like the following. This tracks the current day.
class MenuDish {
private double[] prices = new double[7]; // Assumes day as [0..6]
private int day;
...
public MenuDish setDay(int day) {
this.day = day;
return this;
}
public MenuDish setPrice(double price) {
prices[day] = price;
return this;
}
public double getPrice() {
return prices[day];
}
}

Pass values to parameters

when i trying to do this i got the problem said
Constructor Product in class Product cannot be applied to given types;
required: java.lang.String,int,double; found: java.lang.String;
reason: actual and formal arguments lists differ in length
And i have 2 classes:
import java.text.*
public class Product {
private String name;
private int stock;
private double price;
public Product(String name, int stock, double price) {
this.name = name;
this.stock = stock;
this.price = price;
}
public double sell(int n) {
stock = n;
return stock;
}
public void restock(int n) {
}
#Override
public String toString() {
return stock + name + "at $"+price;
}
}
public class Store {
public static void main(String[] args) {
new Store().use();
}
private Product product;
private Product cashRegister;
public Store() {
product = new Product("Sticky tape");
cashRegister = new Product("Cash register");
}
public void use() {
}
private void sell() {
}
private void restock() {
}
private void viewStock() {
}
private void viewCash() {
}
private void help() {
System.out.println("Menu options");
System.out.println("s = sell");
System.out.println("r = restock");
System.out.println("v = view stock");
System.out.println("c = view cash");
System.out.println("x = exit");
}
}
I understand that i have to declare for Product constructor. But i think i have done it. If anyone know where i got wrong please explain. Thank you!
you do not have constructor with one param, so you can not using this form
product = new Product("Sticky tape");
decare one more constructor with one param or fill all param
product = new Product("Sticky tape", 10, 20.0);
You need to:
overload the constructor
public Product(String name){...}
or create instances of Product using the right and only one constructor uor have:
public Product(String name, int stock, double price)
if you overload then something like this should happen
public Product(String name){
this(name, 0, 0.0);
}
so you call a constructor from the other constructor
This is the time to learn constructor overloading. Overloading comes from OOP.
You can use Overloading to methods and constructors. Overloading means for a same method name you can implement that method
several time with different parameters(number of parameters)
. Actualy not only that,
you can use different data types for parameter.
also can change order of parameter.
keep remember method name must be same.
For the constructor also same thing. If you use for constructor you can add parameters like:
//constructor with one parameter
public Product(String name) {
this.name = name;
this.stock = 0;//or whatever your default value
this.price = 0;//or whatever your default value
}
//constructor with two parameter
public Product(String name, , int stock) {
this.name = name;
this.stock = stock;
this.price = 0;//or whatever your default value
}
public Product(String name, int stock, double price) {
this.name = name;
this.stock = stock;
this.price = price;
}
Like that you can add as many as you want.
Or you can use one constructor and pass argument to match with the implementation of the constructor when creating object. Like below:
product = new Product("Sticky tape", 0, 0);
this is not complete description you can read this to learn more
You have no constructor In Product class that takes single String argument. Create it like so:
public Product(String name) {
this.name = name;
}
In import statement you forgot semicolon:
import java.text.*;
your program is having 3 coding error which include
you forgot the " ; " after " import java.text.* " actually it is not required in your code, you can remove it, nothing will change.
you cannot make class Product as public , because you've made "Store" as your Primary class having main method.So remove public keyword from the Product class.
You didn't create a parameterized constructor
which should be like
public Product(String name){ this.name = name;}
in your product class.
your code will be like after correcting
class Product {
private String name;
private int stock;
private double price;
public Product(String name, int stock, double price) {
this.name = name;
this.stock = stock;
this.price = price;
}
public Product(String name) {
this.name = name;
}
public double sell(int n) {
stock = n;
return stock;
}
public void restock(int n) {
}
#Override
public String toString() {
return stock + name + "at $"+price;
}
}
public class Store {
public static void main(String[] args) {
Store s = new Store();
System.out.println(s.product);
System.out.println(s.cashRegister);
}
private Product product;
private Product cashRegister;
public Store() {
product = new Product("Sticky tape");
cashRegister = new Product("Cash register");
}
}
The errors are in these lines of code:
product = new Product("Sticky tape");
cashRegister = new Product("Cash register");
The Product constructor defined expects:
public Product(String name, int stock, double price)

Array is just printing out last element [closed]

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++;
}

About Java object sort

I experience some issues about sorting price in Java.
I want from high price to low price and from low to high price respectively in my ArrayList.
ArrayList<orderbook> buyerlist=new ArrayList<orderbook>();
I want buyerlist to sort object sequence by price. I tried below but it does not works.
buyerlist.add(new orderbook(orderrecord.get(i).getSide(),orderrecord.get(i).getVolume(),orderrecord.get(i).getPrice()));
Collections.sort(arraylist);
ArrayList<orderbook> sellerlist=new ArrayList<orderbook>();
I want sellerlist can sort object sequence by price
here is my constructor
public class orderbook {
// here i defined three object of this constructor.
// i want sorting this sequence by price. from high to low and low to high respectively.
String side;
int volume;
double price;
public orderbook(String side,int volume,double price){
this.side=side;
this.volume=volume;
// compare price is low then 0 will throw exception
if (volume < 0) {
throw new IllegalArgumentException("volume size illegal");
}
this.price=price;
if (price < 0) {
throw new IllegalArgumentException("price > 0 require");
}
}
public String getSide() {
return side;
}
public void setSide(String side) {
this.side = side;
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
If you have orderbooks in some Collection for example ArrayList, then you can sort them tis way:
Collections.sort(orderBooks, new Comparator<orderbook> {
#Override
public int compare(orderbook ob1, orderbook ob2) {
return o1.getPrice() - o2.getPrice();
}
});

How to create method for withdrawal from store and deliverance to store

I am studying java by myself and I want to get help on exercise which i am doing myself.
The class is called Product which used for representing a product that a small company sells.
It should be possible to store the following information about each product.
The class should have the following methods:
A constructor
A method that returns the units of items in store
A method for deliverance to the store (increases the units of this product)
A method for withdrawal from the store (decreases the units of this product)
Please note that if one of the methods changes the stored items below the order point a message should be printed. It should also be impossible to have a negative amount of items.
I HAVE PROBLEM WITH METHODS. PLEASE TAKE A LOOK MY CODE AND GIVE ME SOME HINTS. I WILL APPRECIATE ALL RESPONDS.
THANK YOU.
Here is my program:
public class Product {
private int productNumber;
private String productName;
private float price;
private int orderPoint;
private int unitsInStore;
private String proDescription;
public Product(int num, String name, float price, int order, int units, String description){
this.productNumber = num;
this.productName = name;
this.price = price;
this.orderPoint = order;
this.unitsInStore = units;
this.proDescription = description;
}
public int getProductNumber() {
return productNumber;
}
public void setProductNumber(int productNumber) {
this.productNumber = productNumber;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getOrderPoint() {
return orderPoint;
}
public void setOrderPoint(int orderPoint) {
this.orderPoint = orderPoint;
}
// a method returns the units in store
public int getUnitsInStore() {
return unitsInStore;
}
public void setUnitsInStore(int unitsInStore) {
this.unitsInStore = unitsInStore;
}
public String getProDescription() {
return proDescription;
}
public void setProDescription(String proDescription) {
this.proDescription = proDescription;
}
public int deliveranceToStore(int store){
unitsInStore = unitsInStore + store;
return unitsInStore ++ ;
}
public int withdrawal(int store){
unitsInStore = store - unitsInStore;
return unitsInStore --;
}
}
The deliveranceToStore method isn't correct. Why are you calling the method recursively?
The method can simply be:
public int deliveranceToStore(int store) {
unitsInStore = unitsInStore + store;
return unitsInStore;
}
If there is no need to return the number of units in store with this call, you should have the return type as void (i.e., if updating the count is sufficient):
public void deliveranceToStore(int store) {
unitsInStore = unitsInStore + store;
}
For withdrawal, you need a similar strategy where unitsInStore is updated:
public void withdrawal(int units) {
if(unitsInStore - units >= 0) {
unitsInStore = unitsInStore - units;
} else {
System.out.println("Unable to withdraw. Insufficient units in store.");
}
}
You can also make the withdrawal method return a boolean which tells whether the withdrawal action was successful. The method, in that case, may look like:
public boolean withdrawal(int units) {
if(unitsInStore - units >= 0) {
unitsInStore = unitsInStore - units;
return true;
} else {
System.out.println("Unable to withdraw. Insufficient units in store.");
return false;
}
}

Categories