the error is not returning the desired statement so I need the thiung to output a positive integer that will be able to duplicate an array list, this would be much appreciate thatnks
#Override
public String getDescription(int itemNumber) {
if(isKnownItemNumber(itemNumber) == true) {
for (recordItem i : itemList) {
if(i.getItemNumber() == itemNumber) {
return description;
}
}
}
return "does not exist";
}
#Override
public void setDescription(String description) {
this.description = description;
}
And here is the main method with the populated arraylist:
package Purchase;
import java.util.*;
import javax.swing.SwingUtilities;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
gui.PosGUI.makeAndShowGUI();
Items.newItems.recordItem(01,"banana",1.00,1);
, "Mayonnaise", 2.00, 0);
}
});
}
}
The usual contract of a getter method is to take no parameters, and return the asked field.
Your getItemNumber method takes a parameter, and returns it as a result, this makes no sense.
public int getItemNumber(int itemNumber) {
return itemNumber;
}
Replace this method with a common getter :
public int getItemNumber() {
return itemNumber;
}
And your isKnownItemNumber method becomes :
public boolean isKnownItemNumber(int itemNumber) {
//assert itemNumber >= 0 : "Item Number must be greater than or equal to 0";
for (recordItem i : itemList) {
if (i.getItemNumber() == itemNumber) {
return true;
}
}
return false;
}
There is probably another mistake in your record-Method. You set the arguments on this, not on the new Item you create. Try this instead:
#Override
public void recordItem(int itemNumber, String description, double unitPrice, int sort) {
if ((isKnownItemNumber(itemNumber) == false) && (unitPrice > 0) && (sort == 0 || sort == 1)) {
Items theItems = new Items();
theItems.itemNumber = itemNumber;
theItems.description = description;
theItems.unitPrice = unitPrice;
theItems.sort = sort;
itemList.add(theItems);
}
}
Another bug: the return i.description; instead of return description;
public String getDescription(int itemNumber) {
if(isKnownItemNumber(itemNumber) == true) {
for (recordItem i : itemList) {
if(i.getItemNumber() == itemNumber) {
return i.getDescription();
}
}
}
return "does not exist";
}
public String getDescription(){
return description;
}
Related
I'm trying to implement this enum into my program so that it will return the String equivalent of the enum value. So for example, if the value of dept = 3, then it will return Printed Books & eBooks.
This is what I have so far and it doesn't seem to work because when I go to my program tester class and I try to add a new OrderItem it says that the constructor is undefined once I enter an integer from 0-5 for the Department part of the constructor.
Does anyone have any ideas about what I am doing wrong?
The enum
public enum Department {
ELECTRICAL(0), PHOTOGRAPHIC(1), COMPUTING(2), BOOKS(3), MUSIC(4), FASHION(5);
private int dNum;
private static String dept[] = { "Electrical & Electronics", "Cameras & Photography", "Laptops, Desktops & Consoles",
"Printed Books & eBooks", "MP3 & CD Music", "Fashion & Accessories" };
private Department(int num) {
dNum = num;
}
public String toString() {
return dept[dNum];
}
}
The program
public class OrderItem {
private int itemCode;
private String itemName;
private String itemSupplier;
private double itemCost;
private Department dept;
private static int nextCode = 1;
public OrderItem(String itemName, String itemSupplier, double itemCost, Department dept) {
setItemName(itemName);
setItemSupplier(itemSupplier);
setItemCost(itemCost);
setDepartment(dept);
}
public void setItemName(String itemName) {
if (itemName != null) {
this.itemName = itemName;
} else {
if (this.itemName == null)
// a default value
this.itemName = "Unknown";
}
}
public void setItemSupplier(String itemSupplier) {
if (itemSupplier != null) {
this.itemSupplier = itemSupplier;
} else {
if (this.itemSupplier == null)
// a default value
this.itemSupplier = "Unknown";
}
}
public void setItemCost(double itemCost) {
this.itemCost = itemCost;
}
public void setDepartment(Department dept) {
this.dept = dept;
}
public void setDepartment(int dept) {
if (dept == 0)
setDepartment(Department.ELECTRICAL);
else if (dept == 1)
setDepartment(Department.PHOTOGRAPHIC);
else if (dept == 2)
setDepartment(Department.COMPUTING);
else if (dept == 3)
setDepartment(Department.BOOKS);
else if (dept == 4)
setDepartment(Department.MUSIC);
else if (dept == 5)
setDepartment(Department.FASHION);
}
public String getItemName() {
return this.itemName;
}
public String getItemSupplier() {
return this.itemSupplier;
}
public double getItemCost() {
return this.itemCost;
}
public String getDepartment() {
return dept.toString();
}
public int useNextCode() {
itemCode = nextCode;
nextCode++;
return itemCode;
}
public String getDetails() {
String result = "Item name: " + getItemName() + "\n Supplier: " + getItemSupplier() + "\n Department: "
+ getDepartment() + "\n Cost: " + getItemCost();
return result;
}
public String toString() {
System.out.println("Item Code: " + useNextCode());
return getDetails();
}
}
You cannot pass Integer (0-5) in your OrderItem Constructor. Instead you need to pass the desired enum. This should work fine.
OrderItem oi = new OrderItem("PenDrive","HP",300.0, Department.ELECTRICAL);
As the title question was how to return the String value for enum, the answer could be to refactor the enum to have description field instead of inner static array of strings, and add a method to retrieve Department by the ordinal value:
public enum Department {
ELECTRICAL("Electrical & Electronics"),
PHOTOGRAPHIC("Cameras & Photography"),
COMPUTING("Laptops, Desktops & Consoles"),
BOOKS("Printed Books & eBooks"),
MUSIC("MP3 & CD Music"),
FASHION("Fashion & Accessories");
private String description;
private Department(String description) {
this.description = description;
}
public String toString() {
return this.description;
}
public static Department byNum(int ordinal) {
if (ordinal < ELECTRICAL.ordinal() || ordinal > FASHION.ordinal()) {
return null; // or throw IllegalArgumentException
}
return Department.values()[ordinal];
}
}
Then method OrderItem::setDepartment(int dept) may be changed like this (instead of multiple if statements):
public static void setDepartment(int dept) {
Optional.ofNullable(Department.byNum(dept))
.ifPresent(OrderItem::setDepartment);
}
I have a problem with Spring Boot.
I am making a REST application, and I have a service that returns a Map(Share, Integer)
Share is a class written by me:
public class Share {
private String ticker;
private String name;
private Double value;
public Share() {
super();
}
public Share(String ticker, String name, Double value) {
super();
this.ticker = ticker;
this.name = name;
this.value = value;
}
public String getTicker() {
return ticker;
}
public void setTicker(String ticker) {
this.ticker = ticker;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((ticker == null) ? 0 : ticker.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Share other = (Share) obj;
if (ticker == null) {
if (other.ticker != null)
return false;
} else if (!ticker.equals(other.ticker))
return false;
return true;
}
#Override
public String toString() {
return "Share [ticker=" + ticker + ", name=" + name + ", value=" + value + "]";
}
}
And the #RestController is:
public class ShareController {
#Autowired
private ShareBussines shareBussines;
#RequestMapping("/getShare/{ticker}")
public Share getShare(#PathVariable("ticker") String ticker) throws BrokerNotFoundException, BrokerArgumentException, BrokerGeneralException {
return shareBussines.getShare(ticker);
}
#RequestMapping(value="/buyShares", method=RequestMethod.POST)
public Map<Share, Integer> buyShares(#RequestBody Map<String,Double> sharesToBuy) throws BrokerGeneralException, BrokerArgumentException, BrokerInsufficientStockException {
return shareBussines.buyShares(sharesToBuy);
}
}
The problem is when I call the service from Postman.
The result is:
{
"Share [ticker=AMZN, name=Amazon, value=259.32126508258295]": 1,
"Share [ticker=GOOGL, name=Google, value=249.35339337497606]": 1,
"Share [ticker=FB, name=Facebook, value=181.15005639608364]": 55
}
The Map key is share.toString()... I want the key to be the share JSON.
I try to remove the toString method from Share class, but the result was:
{
"Share#1eb87f": 1,
"Share#40d9fab": 1,
"Share#8db": 54
}
It is using the Object's toString().
Thank you for your advice.
First, it works as you coded it to work:
#RequestMapping(value="/buyShares", method=RequestMethod.POST)
public Map<Share, Integer> buyShares(#RequestBody Map<String,Double> sharesToBuy) throws BrokerGeneralException, BrokerArgumentException, BrokerInsufficientStockException {
return shareBussines.buyShares(sharesToBuy);
}
Share is a key here. And that is kinda weird. Why not create some object like:
public class ShareResponse {
private Share share;
private Integer someVal; // that's the one you have in your Map as a value
// getters and setters
}
And afterward change your service a bit:
#RequestMapping(value="/buyShares", method=RequestMethod.POST)
public List<ShareResponse> buyShares(#RequestBody Map<String,Double> sharesToBuy) throws BrokerGeneralException, BrokerArgumentException, BrokerInsufficientStockException {
// do your business here, create a list of ShareResponse and return it
return shareBussines.buyShares(sharesToBuy); // instead of this
}
And you should get a valid, nicely 'formatted' JSON. If you need each item to be identifiable by some unique value just add some ID field to ShareResponse.
Does it make any sense?)
Hello folks this may be dumb question but as a beginner am struggling with this how to group values based on id in list, Now let me clarify you briefly am having set of objects like this :
ID:1,UserID:330
ID:2,UserID:303
ID:3,UserID:090
ID:1,UserID:302
ID:2,UserID:306
How my list should look like is(Json Format):
[{"ID":1,"UserID":[330,302]},{"ID":2,"UserID":[303,306]},{"ID":3,"UserID":[090]}]
Now let me post what i have tried so far:
final List<Integer>list=new ArrayList<>();
final List<SpareReturnModel>lisobj=new ArrayList<>();
int duplicate=0;
for(int i=0;i<tView.getSelected().size();i++){
Object o= tView.getSelected().get(i).getValue();
SpareReturnModel asset=(SpareReturnModel) o;
int flag=asset.getFlag();
if(flag==2) {
int warehouseid = asset.getWareHouseID();
asset.setWareHouseID(warehouseid);
int partid = asset.getSerialNoID();
list.add(partid);
}
else {
Log.d("s","no value for header");
}
if(duplicate!=asset.getWareHouseID()){
asset.setParlist(list);
asset.setWareHouseID(asset.getWareHouseID());
lisobj.add(asset);
list.clear();
}
duplicate=asset.getWareHouseID();
}
Gson gson=new Gson();
//this will convert list to json
String value=gson.toJson(listobj);
SpareReturn Model Class:
public class SpareReturnModel {
private Integer SerialNoID;
private String SerialNumber;
private List<Integer>parlist;
public List<Integer> getParlist() {
return parlist;
}
public void setParlist(List<Integer> parlist) {
this.parlist = parlist;
}
public Integer getFlag() {
return flag;
}
public void setFlag(Integer flag) {
this.flag = flag;
}
private Integer flag;
public Integer getWareHouseID() {
return WareHouseID;
}
public void setWareHouseID(Integer wareHouseID) {
WareHouseID = wareHouseID;
}
private Integer WareHouseID;
public Integer getSerialNoID() {
return SerialNoID;
}
public void setSerialNoID(Integer serialNoID) {
SerialNoID = serialNoID;
}
public String getSerialNumber() {
return SerialNumber;
}
public void setSerialNumber(String serialNumber) {
SerialNumber = serialNumber;
}
}
Can someone let me know how to achieve this am struggling with this.
I simplify your class to make solution clearer:
public class SpareReturnModel implements Comparable<SpareReturnModel> {
private Integer id;
private String userId;
public SpareReturnModel(Integer id, String userId) {
this.id = id;
this.userId = userId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Override
public int compareTo(SpareReturnModel other) {
return this.getId().compareTo(other.getId());
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SpareReturnModel model = (SpareReturnModel) o;
if (id != null ? !id.equals(model.id) : model.id != null) return false;
return userId != null ? userId.equals(model.userId) : model.userId == null;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (userId != null ? userId.hashCode() : 0);
return result;
}
}
and add JsonSpareReturnModel
public class JsonSpareRuturnModel implements Comparable<JsonSpareRuturnModel> {
private final List<SpareReturnModel> modelList;
private final Integer id;
public JsonSpareRuturnModel(List<SpareReturnModel> modelList) {
this.modelList = modelList;
this.id = modelList.get(0).getId();
}
private final String toJson() {
return String.format("{\"ID\":%s,\"UserID\":%s}", id, formatUserIdList());
}
private String formatUserIdList() {
StringBuilder builder = new StringBuilder("[");
Iterator<SpareReturnModel> modelIterator = modelList.iterator();
while (modelIterator.hasNext()) {
builder.append(modelIterator.next().getUserId());
if (modelIterator.hasNext()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JsonSpareRuturnModel that = (JsonSpareRuturnModel) o;
return id != null ? id.equals(that.id) : that.id == null;
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
#Override
public int compareTo(JsonSpareRuturnModel other) {
return this.id.compareTo(other.id);
}
#Override
public String toString() {
return toJson();
}
if you need to group by user id you need to sort your models according to id's
and place them to json format model:
public class Main {
public static void main(String[] args) {
List<SpareReturnModel> models = new ArrayList<>(Arrays.asList(
new SpareReturnModel(1, "330"),
new SpareReturnModel(2, "303"),
new SpareReturnModel(3, "090"),
new SpareReturnModel(1, "302"),
new SpareReturnModel(2, "306")
));
Map<Integer, List<SpareReturnModel>> groupById = new HashMap<>();
for (SpareReturnModel model : models) {
List<SpareReturnModel> listById = groupById.get(model.getId());
if (listById == null) {
groupById.put(model.getId(), new ArrayList<>(Arrays.asList(model)));
} else {
listById.add(model);
}
}
List<JsonSpareRuturnModel> jsonList = new ArrayList<>();
for (Map.Entry<Integer, List<SpareReturnModel>> pair : groupById.entrySet()) {
jsonList.add(new JsonSpareRuturnModel(pair.getValue()));
}
System.out.println(jsonList);
final String expected = "[{\"ID\":1,\"UserID\":[330,302]}, {\"ID\":2,\"UserID\":[303,306]}, {\"ID\":3,\"UserID\":[090]}]";
System.out.println(jsonList.toString().equals(expected));
}
}
enum Bags {
SMALL(10832, 10000000), MEDIUM(10833, 100000000), HUGE(10834, 100000000), HEFTY(
10835, 2147000000);
public int id, mAmount;
Bags(int id, int mAmount) {
this.id = id;
this.mAmount = mAmount;
}
public int getId() {
return id;
}
public int getMoneyAmount() {
return mAmount;
}
public Bags getBagConfig(int index) {
for (Bags bag : Bags.values()) {
for (int bagId : bag.getId()) {
if (bagId == index) {
return bag;
}
}
}
return null;
}
}
public static void init(final Client c, final int itemUsed,
final int useWith) {
if (itemUsed == 7 && useWith == 1) {
c.getItems().deleteItem(7, 1);
}
c.eventContainer.addEvent(new CycleEvent(5) {
public void execute() {
c.getItems().addItem(1, 3);
}
});
}
It says: Can only iterate over an array or an instance of java.lang.Iterable
Can someone please help me out with this?
I don't know how to fix this error, the error is on the for loop.
The error message is correct, this
for (Bags bag : Bags.values()) {
for (int bagId : bag.getId()) { // <-- HERE!
if (bagId == index) {
return bag;
}
}
}
Is not legal. I think you wanted
for (Bags bag : Bags.values()) {
if (bag.getId() == index) {
return bag;
}
}
Because getId() returns a single int.
Replace this code:
for (int bagId : bag.getId()) {
if (bagId == index) {
return bag;
}
}
with
if (bag.getId() == index) {
return bag;
}
I have two equals methods in code, yet neither of them work. I made one myself and then I also auto generated one from Eclipse via source. I've run the program multiple times with one or an other and again, neither work.
import java.util.Arrays;
import java.util.Scanner;
import java.math.*;
public class Item {
static //the properties of an Item
double cash=59;
static double sum=0;
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";
}
public Item(int priority, String name, double price) {//constructor with all 3 arguments
this.priority = priority;
this.name = name;
this.price = price;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
//priority must be between 1 and 7
if (priority > 0 && priority <= 7) {
this.priority = priority;
} else {
//otherwise default to 0
System.err.println("Error, enter 1 through 7");
//this.priority = 0;
}
}
public String getName() {
return name;
}
public void setName(String name) {
//would I put equals method here. name.equals.name?
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
//price between 0 and 100 inclusive
if (price >= 0.00) {
if (price <= 100.00) {
this.price = price;
cash = cash-=price;
sum=sum+=price;
} else {
System.err.println("Error: price to high");
}
} else {
System.err.println("Error: price to low");
}
}
public boolean equals(Item otherItem){
if(this.getPriority()==otherItem.getPriority());
System.err.println("Error, Same Priorities detected");
return true;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + priority;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Item)) {
return false;
}
Item other = (Item) obj;
if (priority != other.priority) {
return false;
}
System.err.println("Error, Same Priorities detected");
return true;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Item [Price=").append(getPrice()).append(", ");
if (getName() != null) {
builder.append("Name=").append(getName()).append(", ");
}
builder.append("Priority=").append(getPriority()).append("]");
return builder.toString();
}
public static void main(String[] args) {
Item[] list = new Item[2];
Scanner keyboard = new Scanner(System.in);
for (int i = 1; i <= list.length; i++) {
if(cash==59)
{
System.out.println("You have 59 dollars");
}
Item anItem = new Item(); // new item object created 7 times
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());
list[i-1] = anItem;
System.out.println(Arrays.toString(list));
System.out.println("Cash left "+cash);
System.out.println("Sum of Items "+sum);
if(sum>59)
{System.out.println("Error, you ran out of money");
System.out.println(Arrays.toString(list));}
}
System.out.println( list[1].getPriority());
}
}
This method here is completely biting you in the a**
public boolean equals(Item otherItem){
if(this.getPriority()==otherItem.getPriority());
System.err.println("Error, Same Priorities detected");
return true;
}
First, there's an ; after the if's condition so it's not doing anything and therefore your method is always returning true.
Second, this method overloads the equals(Object) method that you should be overriding and using. Get rid of it.
When overriding methods, annotate them with #Override. With an IDE that will do a check and validate that you are actually trying to override a method.