Here is the problem: Need to distribute N number of queries amongst S number of Servers.Have come up with this.The solution is allocating queries to servers but deleting the previous count of the number of queries the server has.Can someone suggest what I am doing wrong?
public class Servers<T> {
public int serverId;
public ArrayList<Queries> queryList;
public Servers()
{
}
public int getServerId() {
return serverId;
}
public ArrayList<Queries> getqueryList() {
return queryList;
}
public void setqueryList(ArrayList<Queries> queryList) {
this.queryList = queryList;
}
public void setServerId(int serverId) {
this.serverId = serverId;
}
}
Queries class:
public class Queries {
private static final int noOfServers=10;
private String query;
private int queryId;
private int size=0;
private Servers[] ser=new Servers[noOfServers];
//getters and setters for instance variables for Queries class <not included>
public int allocateM(Queries query)
{
ArrayList<Queries> queryList=new ArrayList<Queries>();
int i=size;
if(i < ser.length)
{
qList.add(query);
ser[i].setqueryList(qList);
System.out.println("size" + ser[i].getqueryList());
size++;
}
else if(i==ser.length)
{
size=0;
i=0;
}
return ser[i].serverId;
}
Related
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!
well, I have List<HighscoreEntry> In which your class is this:
public class HighscoreEntry {
private List<String> users;
private int score;
HighscoreEntry(List<String> users, int score) {
this.users = users;
this.score = score;
}
public List<String> getUsers() {
return users;
}
public void setUsers(List<String> users) {
this.users = users;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
Well, what happens, is because in the other class I have this:
public class ScoreboardItemData {
private final static HighscoreComparator comparator = new HighscoreComparator();
private final List<HighscoreEntry> entries;
private final Map<String, Integer> points;
private int scoreType;
private int clearType;
public ScoreboardItemData(int scoreType, int clearType, List<HighscoreEntry> entries, Map<String, Integer> points) {
this.scoreType = scoreType;
this.clearType = clearType;
this.entries = entries;
this.points = points;
}
public List<HighscoreEntry> getEntries() {
return this.entries;
}
public Map<String, Integer> getPoints() {
return this.points;
}
public void addEntry(List<String> users, int score) {
synchronized (this.entries) {
this.entries.add(new HighscoreEntry(users, score));
this.entries.sort(comparator);
}
} }
Well, I already can add new entries, but I want to change ONLY THE SCORE and increase it, to existing data.
And I tried some things, but without success:
Example 1:
synchronized (this.entries) {
for (int i = 0;i < this.entries.size(); i++) {
if (this.entries.get(i).getUsers() == users) {
this.entries.get(i).increaseScore(score);
this.entries.sort(comparator);
} else {
this.entries.add(new HighscoreEntry(users, score));
this.entries.sort(comparator);
}
}
}
This example update the score, but with the loop, he will add more entries and update others, so will always do this loop.
Example 2:
HighscoreEntry entry = (HighscoreEntry) this.entries.stream().filter((x) -> {
return x.getUsers().equals(users);
});
if (entry.getUsers() != null) {
entry.increaseScore(score);
} else {
entry.setUsers(users);
entry.setScore(score);
}
And this one, return this error:
java.lang.ClassCastException: java.util.stream.ReferencePipeline$2 cannot be cast to com.heraproject.wired.data.ScoreboardItemData$HighscoreEntry
at com.heraproject.wired.data.ScoreboardItemData.addEntry(ScoreboardItemData.java:45)
You need to find the right item in the list based on the identifier and looking at HighscoreEntry that identifier is users. This code will update the score for a HighscoreEntry in the list entries if one exists
public void addScore(List<String> users, int score) {
HighscoreEntry entry = entries.filter( e -> (e.getUsers().equals(users))).findFirst().orElse(null);
if (entry != null) {
entry.setScore(score);
}
}
If I understand correctly, all you need is something like this
// int index, someInt;
this.entries.get(index).setScore(someInt);
However, looking at your model, I would think "high score" would be calculated by iterating over a list of potential User objects, each having their own unique scores. Then you set the score on the user, not the entity holding a list of users.
Well,
Use this method
public void updateEntry(List<String> users, int index) {
synchronized (this.entries) {
HighscoreEntry highScoreEntry = this.entries.get(index);
highscoreEntry.setScore(//Update score);
entries.add(index, highscoreEntry);
}
}
I have two classes:
Products:
01; Desinfectante
02; Aerosol
03; Limpia Vidrio
04; Desengrasante
05; Mata mosquitos
06; Mata cucarachas
07; Aceite en aerosol
Instructions:
01;1;Elevar la masa hasta llegar a tal punto;0;10
01;1;Mezclar este material con anterior;1;15
01;2;Relevar;2;5
01;3;Llevar;00;0
02;1;Descripcion;7;2
02;2;Descripcion;6;2
02;2;Descripcion;00;0
03;1;Descripcion;1;1
03;1;Descripcion;2;9
03;2;Descripcion;00;0
03;3;Descripcion;5;2
03;4;Descripcion;6;2
03;4;Descripcion;3;10
04;1;Descripcion;00;0
04;2;Descripcion;1;2
04;3;Descripcion;1;0
04;3;Descripcion;2;2
04;3;Descripcion;3;2
04;4;Descripcion;7;1
04;4;Descripcion;6;2
05;1;Descripcion;7;20
05;1;Descripcion;6;9
05;2;Descripcion;00;0
05;3;Descripcion;1;2
05;3;Descripcion;2;10
06;1;Descripcion;2;12
06;1;Descripcion;4;1
06;1;Descripcion;6;8
06;2;Descripcion;5;4
06;2;Descripcion;7;2
07;1;Descripcion;1;12
07;1;Descripcion;2;2
07;2;Descripcion;3;19
07;2;Descripcion;4;4
07;2;Descripcion;00;2
07;2;Descripcion;5;12
The thing is this: i have to insert the instructions ArrayList into the Products. The link between them is the first number, that is the code of the product.
I tried two things, the first one:
public static ArrayList<Productos> InsertInstInProd(ArrayList<Instrucciones> instructions, ArrayList<Productos> products)
{
for (int i = 0; i < products.size()-1; i++)
{
int n = 0;
for (int j = 0; j < instructions.size()-1; j++)
{
int first = products.get(i).getNumero();
int second = instructions.get(j).getCodProd();
if (first == second)
{
products.get(i).getInstr().get(n).setCodIns(instructions.get(j).getCodIns());
products.get(i).getInstr().get(n).setCodProd(instructions.get(j).getCodProd());
products.get(i).getInstr().get(n).setDescr(instructions.get(j).getDescr());
products.get(i).getInstr().get(n).setMat(instructions.get(j).getMat());
products.get(i).getInstr().get(n).setMatNec(instructions.get(j).getMatNec());
n++;
}
}
n = 0;
}
The second one:
public static ArrayList<Productos> InsertInstInProd(ArrayList<Instrucciones> instructions, ArrayList<Productos> products)
{
for (int i = 0; i < products.size()-1; i++)
{
int n = 0;
for (int j = 0; j < instructions.size()-1; j++)
{
int first = products.get(i).getNumero();
int second = instructions.get(j).getCodProd();
if (first == second)
{
products.get(i).setInstr(instructions);
n++;
}
}
n = 0;
}
return products;
}
You are getting NullPointerException because of
products.get(i).getInstr().get(n).setCodIns(instructions.get(j).getCodIns());
You are not checking whether the list products.get(i).getInstr() has elements or not. When the list is empty and when you are accessing it as products.get(i).getInstr().get(0) it's throwing you NullPointerException because trying to get the first element of an empty list. So before you do this operation, make sure that products.get(i).getInstr() is not empty.
If they are of same type, you can directly add the whole arraylist :
products.get(i).getInstr().addAll(instructions); // again make sure that is not empty.
If you just want to replac, use :
products.get(i).setInstr(instructions.get(j));
Products Class
package productsandinstructions;
import java.util.List;
public class Product {
private int productId;
private String productName;
private List instructions;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public List getInstructions() {
return instructions;
}
public void setInstructions(List instructions) {
this.instructions = instructions;
}
}
Instruction Class
package productsandinstructions;
public class Instruction {
private int productId;
private int instructionId;
private String instDesc;
private int mat;
private int matNec;
private boolean done;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getInstructionId() {
return instructionId;
}
public void setInstructionId(int instructionId) {
this.instructionId = instructionId;
}
public String getInstDesc() {
return instDesc;
}
public void setInstDesc(String instDesc) {
this.instDesc = instDesc;
}
public int getMat() {
return mat;
}
public void setMat(int mat) {
this.mat = mat;
}
public int getMatNec() {
return matNec;
}
public void setMatNec(int matNec) {
this.matNec = matNec;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
}
Main Class
package productsandinstructions;
import java.util.List;
public class ProductsAndInstructionsMain {
private List products;
private List instructions;
public List getProducts() {
return products;
}
public void setProducts(List products) {
this.products = products;
}
public List getInstructions() {
return instructions;
}
public void setInstructions(List instructions) {
this.instructions = instructions;
}
public static void main(String[] args) {
ProductsAndInstructionsMain main = new ProductsAndInstructionsMain();
main.mergeProductsAndInstructions();
}
public void mergeProductsAndInstructions() {
for (Product product : products) {
for (Instruction instruction : instructions) {
if ((!(instruction.isDone())) && (instruction.getProductId() == product.getProductId())) {
product.getInstructions().add(instruction);
instruction.setDone(true);
}
}
}
}
}
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);
public class Table{
private String column[];
private String dataType[];
private boolean PK[];
private boolean NN[];
private int count;
public Table()
{
count =0;
}
public void AddColumn(String name,String dtype,boolean pk,boolean nn)
{
column[count]=name;
dataType[count]=dtype;
PK[count]=pk;
NN[count]=nn;
count++;
}
public void Display(Table T)
{
}
public void DeleteColumn(String name)
{
if(count==0){return;}
else if(count ==1)
{
if(name==column[0])
column[0]=null;
dataType[0]=null;
count--;
return;
}
else
for(int i=0;i<count;i++)
{
if(name==column[i])
{
column[i]=column[count-1];
dataType[i]=dataType[count-1];
PK[i]=PK[count-1];
NN[i]=NN[count-1];
}
}
}
This is my table class; as im designing an Entity table and for keeping column Name data type etc. Is this class and its private attributes correct or should i break this into more classes eg attributes.
I think that you should create Column class.
I will do it in this way (of course it can be done better):
public class DataType {
public static String DATA_TYPE_1 = "dataType1";
public static String DATA_TYPE_2 = "dataType2";
public static String DATA_TYPE_3 = "dataType3";
}
public class Column() {
private String name;
private DataType dataType;
private boolean PK;
private boolean NN;
// getters and setters
}
public class Table {
private ArrayList<Column> columns;
public Table() {
columns = new ArrayList<Column>();
}
public boolean AddColumn(Column column) {
columns.add(column);
}
public boolean DeleteColumn(String name) {
for (Column c : columns) {
if (c.getName().equals(name)) {
return columns.remove(column);
}
}
return false;
}
}