How to compare group of Strings - java

I have the following code..
WorkPackage spack=(WorkPackage)primaryBusinessObject;
WTSet res;
WTPart spart=null;
String state=null;
res=wt.facade.persistedcollection.PersistedCollectionHelper.service.getAllMembers(spack);
System.out.println("the values are "+res);
java.util.Iterator iter=res.persistableIterator();
while(iter.hasNext())
{
spart=(wt.part.WTPart) iter.next();
wt.lifecycle.LifeCycleState st=spart.getState();
String state=st.toString(); //Lifecycle state of part object
}
if(state.contains("APPROVED"))
result="Proceed";
In the above code I'm passing a windchill package and it may have muliple number of WTPart objects.Each part may have different life cycle states.What I want is if every part state is "APPROVED" means it should proceed in my workflow.
For eg.
LifeCycle states of
Part1=IN WORK
Part2=IN REVIEW
Part3=APPROVED
Part4=APPROVED
Part5=CANCELED
I want to compare all the objects from my package is APPROVED I can store these in vector or a arraylist and I don't know how to compare all the objects from that.My above code will pass if any one of objects state is APPROVED.I know this question not related to windchill.Somebody help me out of it

If you store all of the states in an ArrayList<String> states then you can test if they are all APPROVED using something like:
boolean allApproved = true;
for(int i = 0; i < states.size(); i++) {
if(!states.get(i).equals("APPROVED") {
allApproved = false;
}
}
At the end of the for loop, if allApproved is still true, you're good to go.

Related

Java adding an ArrayList to Existing Object

I'm having some trouble with one of my methods. A brief overview of what my method is supposed to do. Here's what I have so far.
public boolean addGame(String team1, String team2) {
boolean result;
if (team1.equals(team2))
result = false;
}
if (a game between two parameter teams has previously been added by
earlier call to addGame){
result = false;
}
else {
result = true;
}
I want my method to return false if a game between two parameter teams has previously been added to the conference object by an earlier call to addGame and
if the name of team1 and team2 are the same name.
My issue is the syntax for what's inside of my second if statement. Not sure how to go about it.
Thanks in advance for all the help.
Depends on how long you plan on saving the information. If it is just in the runtime, you can do something such as saving the two teams to an array.
If you want to save it for a longer time, you need some way of persisting the information, possibly a table in a database?
Then, you can query to data and check if the combination existed already.
You can create a history of the added teams:
ArrayList<String> history = new ArrayList<String>();
//As you add the teams
history.add(teamName); //add to history as well
//To check if teams already exist or added before
if(history.contains(team1) || history.contains(team2)){
return false;
}
If you have an ArrayList called games, and the games are stored in the format "team1;team2", then you can do games.indexOf(team1 + ";" + team2) == -1 for the if statement.

Searching Array list of objects

I have an array list in a class the array is called realtorList. From my main class I store objects with realtor data to the realtorList.
My data that is stored to a text file and is read in the first line.
This is the first element in the realtorList after I store the first line of data.
[Realtor{licenseNumber=AA1111111, firstName=Anna, lastName=Astrid, phoneNumber=111-111-1111,
commission=0.011}]
When I read the next line of data from the input file I need to see if the licenseNumber in bold already exists in the realtorList. I am having trouble figuring out how to go about doing this.
For example if the next realtor data license number is AA1111111 how do I check the realtorList for AA1111111 which does exist for this example.
A really simple way to do this would be to have a String ArrayList running alongside (for example, one called licenses) and use an if statement with indexOf to return if that license value is already in the List. Since the licenses ArrayList only has one value it can be easily searched with indexOf.
An example would be
private boolean checkLicense (String licenseNumber) {
int i = licenses.indexOf(licenseNumber);
if(i == -1) {
return false;
} else {
return true;
}
}
Similar code works in one of my projects where a dynamic List of motors for a robot checks to see if there's already a motor with the listed port before adding a new one.
Another method could use a for loop for a linear search such as
private boolean checkLicense (String licenseNumber) {
for(int i = 0; i < (realtorList.size() - 1); i++) {
if (licenseNumber.equals(realtorList[i].getLicenseNumber())) {
return true;
}
}
return false;
}
This would perform a linear search of each and every object until it finds it (it would need to be in a method like the one for the example above to work this way)

Checking that at least Value in HashMap matches?

I am trying to figure out how to iterate through my HashMap to see if at least one Value in it matches what I am looking for.
for(int i=0; i<allDogsInkennels.size(); i++){
Map<String, DogStatus> allDogsStatus = allDogsInKennels.get(i).getAllStatuses();
}
How can I add an If statement / loop here to check that at least one of the statuses matches e.g. "APPROVED".
Note: String= the Dogs Id
,DogStatus= Enum showing dog's status
if (allDogsStatus.containsValue(DogStatus.APPROVED)) {
// ...
}
You can iterate over the map and stop if you hit a match:
boolean found = false;
for (DogStatus value : allDogsStatus.values()) {
if (value == DogStatus.APPROVED) {
found = true;
break;
}
}
Even better is to refactor the above into a function that return the boolean.
Edit: I feel dumb for not remembering the containsValue method. That's probably the best approach, even though complexity is the same.

Creating a for loop to do a to.String to my array list

Im currently making a shopping store application, I have 6 classes. 1 for products where it defines the fields for products in the store, another for the shopping basket, one for the GUI and the rest for listeners.
I need to be able to run a method that runs through an array list and running the to.String method on it and returning it as String. Here is what I have at the moment,
private ArrayList<OrderItem> basket = new ArrayList<OrderItem>();
public String createArrayText () {
for (int i = 0; i < OrderItem.size(); i++){
if (i == OrderItem.size() - 1){
return ordersText ;
}
}
}
ordersText is a variable I made at the top of my shopping cart class.
This was my first start at it however I'm getting a error on the .size and obviously missing some key components.
One thing Extra is that each item created is added to the array list, each item has a unique order number.
Arrays.toString(basket);
Is that what you're looking for? If not, you need to explain a little better.
You generally speaking loop over a List like this (Java 7, it's called enhanced for loop):
for (TYPE TEMP_NAME : COLLECTION) {
}
That's the overall syntax. TYPE is the type of item in the list, yours are Object's in the given code. TEMP_NAME is the temporary name you want each entry to be referred as. COLLECTION is the list/array/stack/queue or other Collection.
Concretely:
for (Object o : basket) {
// if basket contains 10 entries the line will run 10 times. each new run contains a different object with name o
}
Normally when building strings it's preferred to use StringBuilder. We can skip that as it's "only" performance that you gain from it. We'll do it with a regular String. So:
Create an empty string that will get longer and longer
Loop the collection/array/list
Append each object's .toString() to the string from 1)
e.g.
String myReturnString = "";
for (Object o : basket) {
myReturnString = myReturnString + " // " + o.toString();
}
return myReturnString;
Notes:
Your loop with an index is fine. You can do it that way too, if you want to.
The line of code that appends the string has a " // " separator between each entry. You can pick whatever you like. You can also simplify it to be myReturnString += " // " + o.toString();

Advice on Java program

My java project required that I create an array of objects(items), populate the array of items, and then create a main method that asks a user to enter the item code which spits back the corresponding item.
It took me a while to figure out, but I ended up "cheating" by using a public variable to avoid passing/referencing the object between classes.
Please help me properly pass the object back.
This is the class with most of my methods including insert and the find method.
public class Catalog {
private Item[] itemlist;
private int size;
private int nextInsert;
public Item queriedItem;
public Catalog (int max) {
itemlist = new Item[max];
size = 0;
}
public void insert (Item item) {
itemlist[nextInsert] = item;
++nextInsert;
++size;
}
public Item find (int key) {
queriedItem = null;
for (int posn = 0; posn < size; ++posn) {
if (itemlist[posn].getKey() == key) queriedItem = itemlist[posn];
}{
return queriedItem;
}
}
}
This is my main class:
import java.util.*;
public class Program {
public static void main (String[] args) {
Scanner kbd = new Scanner (System.in);
Catalog store;
int key = 1;
store = new Catalog (8);
store.insert(new Item(10, "food", 2.00));
store.insert(new Item(20, "drink", 1.00));
while (key != 0) {
System.out.printf("Item number (0 to quit) ?%n");
key = kbd.nextInt();
if (key == 0) {
System.out.printf("Exiting program now!");
System.exit(0);
}
store.find(key);
if (store.queriedItem != null) {
store.queriedItem.print();
}
else System.out.printf("No Item found for %d%n", key);
}
}
}
Thanks I appreciate the help!!!!!!
store.find(key); returns an Item you should use it and delete the public field from Catalog
public Item find (int key) {
Item queriedItem = null;
//....
}
Item searched = store.find(key);
if (searched != null)
searched.print();
else
System.out.printf("No Item found for %d%n", key);
Remove your use of queriedItem entirely and just return the item from find: Replace
store.find(key);
if (store.queriedItem != null){store.queriedItem.print();}else System.out.printf("No Item found for %d%n", key);
With
Item foundItem = store.find(key);
if (foundItem != null) {
foundItem.print();
} else System.out.printf("No Item found for %d%n", key);
Well, here are some suggesetions (choose complexity at your own discretion, but all of them is highly recommended):
Research Properties, for example here. Or XML. You could populate the array with values from a configuration file for greater flexibility.
Use constanst for literals in your code (where they are necessary).
Create an ApplicationFactory the initializes the whole application for you. Things like this need to be separated from your domain logic.
Create a UserInputProvider interface so you can easily change the way the input of the user is read without affecting anything else. Implement it with a ConsoleInputProvider class for example.
In general, try using interfaces for everything that's not a pure domain object (here, the only one you have is probably Item).
Try to keep your methods as short as possible. Instead of doing many things in a method, have it invoke other methods (grouping related logic) named appropriately to tell what it is doing.
If you're not allowed to cheat and use List or a Map, devise your own implementation of one, separating data structure and handling from the logic represented by Catalog (i.e. Catalog in turn will delegate to, for example, Map.get or equivalent method of your data structure implementation)
Your main should basically just have ApplicationFactory (or an IoC framework) to build and initialize your application, invoke the UserInputProvider (it should not know the exact implementation it is using) to get user input, validate and convert the data as required, invoke Catalog to find the appropriate Item and then (similarly to the input interface) send the result (the exact data it got, not some string or alike) to some implementation of a SearchResultView interface that decides how to display this result (in this case it will be a console-based implementation, that prints a string representing the Item it got).
Generally, the higher the level of decoupling you can achieve, the better your program will be.
The Single Responsibility Principle states: " every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class". This is also true for methods: they should have one and only one well defined task without any side effects.

Categories

Resources