Can only iterate over an array - java

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

Related

how to ignore 2 users with same id and just print the first user?

I'm making a group class in java but I have a problem that If the user tries to do an operation that could violate the state of objects, I don't know how to ignore the operation
and make the application display an error message
Here is the code:
import java.util.ArrayList;
public class Group {
private static int staticNumber = 0;
private int groupNumber;
private Trainer trainer;
private String sportName;
private ArrayList<Kid> kids;
private final static int MAX_LIMIT = 10;
public Group(Trainer t, String sport) {
groupNumber = staticNumber++;
this.trainer = t;
this.sportName = sport;
kids = new ArrayList<>();
}
public static int getStaticNumber() {
return staticNumber;
}
public int getGroupNumber() {
return groupNumber;
}
public Trainer getTrainer() {
return trainer;
}
public String getSportName() {
return sportName;
}
public ArrayList<Kid> getKids() {
return kids;
}
public boolean addKid(Kid k) {
if (kids.size() < MAX_LIMIT) {
kids.add(k);
return true;
} else {
return false;
}
}
public boolean removeKid(Kid k) {
return kids.remove(k);
}
}
Adding a println() before the return will output the message in console:
public boolean addKid(Kid k) {
if (kids.size() < MAX_LIMIT) {
kids.add(k);
return true;
} else {
System.out.println("User wasn't Added Try again");
return false;
}
}
Alternatively, if you would like to throw an exception, which would terminate your run of the code:
public boolean addKid(Kid k) {
if (kids.size() < MAX_LIMIT) {
kids.add(k);
return true;
} else {
throw new ArrayIndexOutOfBoundsException("Too many Kids");
}
}
Hope this helped!

How to group values in list based on id in java?

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

Looping through ArrayList to get an item number

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

Class cast Exception while using Comparable interface

When I am trying to execute the below code,the compiler is throwing error at line 13 as "java.lang.ClassCastException". Can someone let me know what's wrong with below code?
package chapter11;
import java.util.*;
public class ComparableExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
Item[] items = new Item[3];
items[0] = new Item(102, "Duct Tape");
items[1] = new Item(103, "Bailing Wire");
items[2] = new Item(104, "Chewing Gum");
Arrays.sort(items);
for (Item i : items) {
System.out.println(i.getNumber() + ":" + i.getDescription());
}
}
}
interface Comparable {
int compareTo(Object o);
}
class Item implements Comparable {
private int number;
private String description;
public Item(int number, String description) {
this.number = number;
this.description = description;
}
public int getNumber() {
return number;
}
public String getDescription() {
return description;
}
public int compareTo(Object o) {
Item i = (Item) o;
if (this.getNumber() < i.getNumber())
return -1;
if (this.getNumber() < i.getNumber())
return 1;
return 0;
}
}
Any help is appreciated,
Thanks!!
Remove your Comparable interface, and use the Comparable interface from the Java api.
And also, maybe you can change
public int compareTo(Object o) {
Item i = (Item) o;
if (this.getNumber() < i.getNumber())
return -1;
if (this.getNumber() < i.getNumber())
return 1;
return 0;
}
into :
public int compareTo(Object o) {
Item i = (Item) o;
if (this.getNumber() < i.getNumber())
return -1;
if (this.getNumber() > i.getNumber())
return 1;
return 0;
}

Sorting values with Comparator changes all the values with that object

I am working in an android application I want to sort a List of Objects with an Object Property. I have sorted it successfully but when I sort it all the List with that object changes the value to same as the sorted value
Please look into ma code :
SortedSet<Caseload> removeDuplicateClientName = new TreeSet<Caseload>(
new Comparator<Caseload>() {
#Override
public int compare(Caseload caseload0, Caseload caseload1) {
return caseload0.ClientName.compareTo(caseload1.ClientName);
}
});
// Getting the list of values from web service
mLISTCaseloadsHeads = parsedXML.getCaseLoadValues("get_Caseload_ClientServiceGroupID", param);
List<Caseload> newBackUp=mLISTCaseloadsHeads ;
Iterator<Caseload> iterator = mCaseloadsHeads.iterator();
while (iterator.hasNext()) {
removeDuplicateClientName.add(iterator.next());
}
mCaseloadsHeads.clear();
mCaseloadsHeads.addAll(removeDuplicateClientName);
The List newBackUp also changes the value to the same as sorted List
Caseload class:
public class Caseload implements Comparable<Caseload> {
public int BusClientLogID;
public int ClientID;
public int ClientStatus;
public int ClientServiceGroup_ClientSiteTherapyID;
public String ClientName;
public String TimeArrive;
public String TimeDepart;
public String SignOutTime;
public String SignInTime;
public String ServiceCompletedCount;
public Boolean ShowFooter = false;
public int getBusClientLogID() {
return BusClientLogID;
}
public void setBusClientLogID(int busClientLogID) {
BusClientLogID = busClientLogID;
}
public int getClientID() {
return ClientID;
}
public void setClientID(int clientID) {
ClientID = clientID;
}
public int getClientStatus() {
return ClientStatus;
}
public void setClientStatus(int clientStatus) {
ClientStatus = clientStatus;
}
public int getClientServiceGroup_ClientSiteTherapyID() {
return ClientServiceGroup_ClientSiteTherapyID;
}
public void setClientServiceGroup_ClientSiteTherapyID(
int clientServiceGroup_ClientSiteTherapyID) {
ClientServiceGroup_ClientSiteTherapyID = clientServiceGroup_ClientSiteTherapyID;
}
public String getClientName() {
return ClientName;
}
public void setClientName(String clientName) {
ClientName = clientName;
}
public String getTimeArrive() {
return TimeArrive;
}
public void setTimeArrive(String timeArrive) {
TimeArrive = timeArrive;
}
public String getTimeDepart() {
return TimeDepart;
}
public void setTimeDepart(String timeDepart) {
TimeDepart = timeDepart;
}
public String getSignOutTime() {
return SignOutTime;
}
public void setSignOutTime(String signOutTime) {
SignOutTime = signOutTime;
}
public String getSignInTime() {
return SignInTime;
}
public void setSignInTime(String signInTime) {
SignInTime = signInTime;
}
public String getServiceCompletedCount() {
return ServiceCompletedCount;
}
public void setServiceCompletedCount(String serviceCompletedCount) {
ServiceCompletedCount = serviceCompletedCount;
}
#Override
public int compareTo(Caseload compareCaseload) {
int busClientLogID = ((Caseload) compareCaseload).getBusClientLogID();
return busClientLogID - this.BusClientLogID;
}
}
Please give me a solution.
I doubt the return statement associated with your compare function in the comparator.
You should go by this approach to get the right ordering :
#Override
public int compare(YourClass lhs, YourClass rhs) {
YourClass p1 = (YourClass) lhs;
YourClass p2 = (YourClass) rhs;
int first = p1.ClientName; //use your getter if you want
int second = p2.ClientName;
if (second < first) {
return 1;
}
else if (second > first) {
return -1;
}
else {
return 0;
}
}
If you go by this approach I guess you will get the required ordering after sort.
Edit:
Now I have got the issue, you are using a reference of the original list in newBackup and its not a new list that is why this is happening, use this and you are good to go.
List<Caseload> newBackUp=new ArrayList<Caseload>(mLISTCaseloadsHeads);

Categories