About Java object sort - java

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

Related

Creating a Shoe object

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

Reduse integer everytime an new object is added to arraylist

I have a class of Person with an ArrayList of the class Groceries.
Let's name the Arraylist shoppingBag.
Student and Groceries has one field each, int money and int price.
The specific amount of money and price is up to you when initializing new objects.
So every time a Person adds an object of Groceries to his shoppingBag, the amount of money he has needs to be reduced with the total price of groceries added to the bag.
How do you do that?
So, let my try to understand what you want (as I do the same for my clients)
You have a class Groceries with price field:
class Groceries {
private int price;
public Groceries(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
#Override
public String toString() {
return "Groceries{" +
"price=" + price +
'}';
}
}
And class person with int money filed and shopping bag field as List of Groceries:
class Person {
private List<Groceries> shoppingBag = new ArrayList<>();
private int money;
public Person(int money) {
this.money = money;
}
public List<Groceries> getShoppingBag() {
return shoppingBag;
}
public int getMoney() {
return money;
}
}
Firstly you create an instance of Person with some mount of money: Person person = new Person(150);
And then each time when you add a groceries to the shopping bag, like person.getShoppingBag().add(new Groceries(10)); you do want to reduce amount of money from the person instance.
So, If I am correct, you need to implement several things:
1) You should forbid adding groceries to the shopping bag with the way described before. We need to throw an exception when someone tries to add an element to the List via getter. It can be implemented using an Unmodifiable copy of your list:
public List<Groceries> getShoppingBag() {
List<Groceries> bag = new UnmodifiableArrayList<>(shoppingBag.toArray(new Groceries[shoppingBag.size()]), shoppingBag.size());
return bag;
}
or a little bit nicely and shortly using Guava:
public List<Groceries> getShoppingBag() {
List<Groceries> bag = ImmutableList.copyOf(shoppingBag);
return bag;
}
2) Add a method that will add a groceries directly. You can also throw an exception if there is no enough money to not have negative balance:
public void addToShoppingBag(Groceries groceries) {
if (0 > money - groceries.getPrice()) {
throw new IllegalStateException("You have not enough money!");
}
shoppingBag.add(groceries);
money -= groceries.getPrice();
}
3) Probably you will need to have possibility to add some money:
private void addMoney(int amout) {
money += amout;
}
Please see the completely demo example:
class Demo {
public static void main(String[] args) throws IOException {
Person person = new Person(42);
try {
System.out.println(person.getMoney());
person.addToShoppingBag(new Groceries(12));
person.addToShoppingBag(new Groceries(20));
person.addToShoppingBag(new Groceries(5));
System.out.println(person.getMoney());
System.out.println(person.getShoppingBag());
person.getShoppingBag().add(new Groceries(1));
} catch (UnsupportedOperationException e) {
e.printStackTrace();
}
try {
person.addToShoppingBag(new Groceries(66));
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
class Person {
private List<Groceries> shoppingBag = new ArrayList<>();
private int money;
public Person(int money) {
this.money = money;
}
public List<Groceries> getShoppingBag() {
List<Groceries> bag = ImmutableList.copyOf(shoppingBag);
return bag;
}
public void addToShoppingBag(Groceries groceries) {
if (0 > money - groceries.getPrice()) {
throw new IllegalStateException("You have not enough money!");
}
shoppingBag.add(groceries);
money -= groceries.getPrice();
}
private void addMoney(int amout) {
money += amout;
}
public int getMoney() {
return money;
}
}
class Groceries {
private int price;
public Groceries(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
#Override
public String toString() {
return "Groceries{" +
"price=" + price +
'}';
}
}
PS: Please next time describe some examples of code and demos to get an answer :)

CompareTo Function Issue

Help I cant figure out the compareTo Function. This is what I have to do: Write a compareTo function that can be used to place the products in order according
to their part numbers. That is, a part number that is later in alphabetical
order is greater than a part number that is earlier in alphabetical order.
This is my code:
public class ProductType implements Comparable<ProductType> {
private String partnum;
private double price;
private int stock;
public ProductType(String partnum, double price, int stock) {
this.partnum = partnum;
this.price = price;
this.stock = stock;
}
public ProductType() {
partnum = "";
price = 0;
stock = 0;
}
public void setNum(String partnum) {
this.partnum = partnum;
}
public void setPrice(double price) {
this.price = price;
}
public void setStock(int stock) {
this.stock = stock;
}
public String getNum() {
return partnum;
}
public double getPrice() {
return price;
}
public int getStock() {
return stock;
}
public int compareTo(ProductType otherType) throws NullPointerExeption {
if (otherType == null)
throw new NullPointerException();
return (this.getNum().compareTo.otherType.getNum());
}
public String toString() {
String result = "" + this.getNum();
return result;
}
}
change your return statement
return (this.getNum().compareTo.otherType.getNum());
to
return (this.getNum().compareTo(otherType.getNum()));
because compareTo() is method.
before calling compareTo() method check whether
null != this.getNum()
otherwise you will get NPE.

My getStats method pops up with infinity numbers

In Java, my basketball players keep sending back "infinity" in my getStats method and I do not know why. Can someone help please? I needed getters and setters so I have that. I am suppose to test the getStats() methods but it errors out every time. At first it was NaNa now its infinity
public class BasketBallPlayer
{
// instance variables - replace the example below with your own
private String name;
private int height;
private int weight;
private double freeThrowsAttempted;
private double freeThrowsMade;
private double twoPointFieldGoalsAttempted;
private double twoPointFieldGoalsMade;
private double threePointersAttempted;
private double threePointersMade;
private int turnovers;
private int assist;
private String stats;
public BasketBallPlayer(String name, int height, int weight, double freeThrowsMade, double twoPointFieldGoalsAttempted,double twoPointFieldGoalsMade, double threePointersAttempted, double threePointersMade, int assist, int turnovers)
{
//identifies the age, name, height-in., weight-lbs
this.name=name;
this.height=height;
this.weight=weight;
this.freeThrowsAttempted=freeThrowsAttempted;
this.freeThrowsMade=freeThrowsMade;
this.twoPointFieldGoalsAttempted=twoPointFieldGoalsAttempted;
this.threePointersMade=threePointersMade;
this.turnovers=turnovers;
this.assist=assist;
}
public BasketBallPlayer(int weight, int height, String name)
//identifies the weight(lbs.), height(inches) and String name
{
//identifies the name, height-in., weight-lbs
this.name=name;
this.height=height;
this.weight=weight;
}
//Sets the Name
public void setName(String name)
{
this.name=name;
}
//Sets the Height
public void setHeight (int height)
{
this.height=height;
}
//Sets the Weight
public void setWeight (int weight)
{
this.weight=weight;
}
//Sets the Free Throws Attempted
public void setFreeThrowsAttempted( double freeThrowsAttempted)
{
this.freeThrowsAttempted=freeThrowsAttempted;
}
//Sets the Free Throws Made
public void setFreeThrowsMade(double freeThrowsMade)
{
this.freeThrowsMade=freeThrowsMade;
}
// Sets two Point Field Goals Attempted
public void setTwoPointFieldGoalsAttempted (double twoPointFieldGoalsAttempted)
{
this.twoPointFieldGoalsAttempted=twoPointFieldGoalsAttempted;
}
public void setTwoPointFieldGoalsMade (double twoPointFieldGoalsMade)
{
this.twoPointFieldGoalsMade=twoPointFieldGoalsMade;
}
public void setThreePointerAttempted(double threePointersAttempted)
{
this.threePointersAttempted=threePointersAttempted;
}
public void setThreePointersMade(double threePointersMade)
{
this.threePointersMade=threePointersMade;
}
public void setTurnovers(int turnovers)
{
this.turnovers=turnovers;
}
public void setAssist(int assist)
{
this.assist=assist;
}
//Returns a Name
public String getName()
{
return name;
}
public int getHeight ()
{
return height;
}
public int getWeight ()
{
return weight;
}
public double getFreeThrowsAttempted()
{
return freeThrowsAttempted;
}
public double getfreeThrowsMade()
{
return freeThrowsMade;
}
public double getTwoPointFieldGoalsAttempted ()
{
return twoPointFieldGoalsAttempted;
}
public double getTwoPointFieldGoalsMade ()
{
return twoPointFieldGoalsMade;
}
public double getThreePointerAttempted()
{
return threePointersAttempted;
}
public double getthreePointersMade()
{
return threePointersMade;
}
public int getTurnovers()
{
return turnovers;
}
public int gettAssist()
{
return assist;
}
/** The geStats Method allows you to get all information on the player in print. All Percentages
*
*/
public void getStats()
{
double Percentage1;
double Percentage2;
double Percentage3;
Percentage1=(double)((twoPointFieldGoalsMade*100)/twoPointFieldGoalsAttempted);
Percentage2=((double)(threePointersMade*100)/threePointersAttempted);
Percentage3=((double)((freeThrowsMade*100)/freeThrowsAttempted));
System.out.println("*************************");
System.out.println("BasketBall Player Name:" + name);
System.out.println("Field Goal Percentage:" + Percentage1 +"%");
System.out.println("3 Pointer Percentage:" + Percentage2 +"%");
System.out.println("Free Throw Percentage:" + Percentage3 +"%");
System.out.println("Assist to Turnover Ration:" + assist/turnovers);
System.out.println("*************************");
}
}
First, you should not be using doubles for these number. It just accounts to inefficiency and makes no sense. However, when using ints, you have to note that you cannot directly get a percentage when dividing two ints. This piece of code should work, you may want to include some code that checks that the divisors are not 0.
private int freeThrowsAttempted;
private int freeThrowsMade;
private int twoPointFieldGoalsAttempted;
private int twoPointFieldGoalsMade;
private int threePointersAttempted;
private int threePointersMade;
...
double percentage1 = (twoPointFieldGoalsMade * 100F) / twoPointFieldGoalsAttempted;
double percentage2 = (threePointersMade * 100F) / threePointersAttempted;
double percentage3 = (freeThrowsMade * 100F) / freeThrowsAttempted;

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