Adding values to HashMap - java

I'm currently adding values to a HashMap<String, SpriteSheetAnimation>. I am also adding to the hashmap in the LoadFile method of my input class. When I add to the hashmap, which is part of the class GameObject that a reference is created for in the FileLoader. I alter the hashmap, adding keys and values to it, and everything is okay.
I then proceed to add the GameObject object to an objectManager where I store all of the objects for my game. When I reference the object in the ArrayList, however, the SpriteSheetAnimation value and the key of that value that I added in the file loader are no longer present. If I try to access them from within the FileLoader after adding them they are there though. I am a little confused. Is there possibly a scope issue going on here?
I've just realized something that may help you help me..(the System.out.println)
If I run this the component is not there when i try to fetch with the .toString
private void LoadControllableEntity(XMLEventReader eventReader, int x, int y)
{
entities.ControllableEntity entity = new entities.ControllableEntity(x, y);
entity.addComponent(new components.InputComponent(entity), "input");
while(eventReader.hasNext())
{
try
{
XMLEvent event = eventReader.nextEvent();
if(event.isEndElement())
{
if(event.asEndElement().getName().getLocalPart().equals("ControllableEntity"))
{
break;
}
} else if(event.isStartElement())
{
String element = (String) event.asStartElement().getName().getLocalPart();
if(element.equals("renderable"))
{
entity.addComponent(new components.Renderable(entity), "renderer");
}
else if(element.equals("animationComponent"))
{
entity.addComponent(getAnimationComponent(entity, event.asStartElement().getAttributes(), eventReader), "animation");
}
}
} catch(XMLStreamException e)
{
e.printStackTrace();
}
System.out.println(entity.getComponent("animation").toString());
managers.ObjectManager.getInstance().addObject(entity);
}
}
When I run this code though.. It can fetch the component fine(notice I've changed where I'm trying to get the component at.)
private void LoadControllableEntity(XMLEventReader eventReader, int x, int y)
{
entities.ControllableEntity entity = new entities.ControllableEntity(x, y);
entity.addComponent(new components.InputComponent(entity), "input");
while(eventReader.hasNext())
{
try
{
XMLEvent event = eventReader.nextEvent();
if(event.isEndElement())
{
if(event.asEndElement().getName().getLocalPart().equals("ControllableEntity"))
{
break;
}
} else if(event.isStartElement())
{
String element = (String) event.asStartElement().getName().getLocalPart();
if(element.equals("renderable"))
{
entity.addComponent(new components.Renderable(entity), "renderer");
}
else if(element.equals("animationComponent"))
{
entity.addComponent(getAnimationComponent(entity, event.asStartElement().getAttributes(), eventReader), "animation");
System.out.println(entity.getComponent("animation").toString());
}
}
} catch(XMLStreamException e)
{
e.printStackTrace();
}
managers.ObjectManager.getInstance().addObject(entity);
}
}

The problem with your first code-snippet is that you retrieve and print the animation entity on every pass through the loop — even before you add that entity — whereas in your second code-snippet you only retrieve and print it immediately after adding the entity, so obviously it doesn't have that problem.
I think you want to change this:
System.out.println(entity.getComponent("animation").toString());
managers.ObjectManager.getInstance().addObject(entity);
}
to this:
}
System.out.println(entity.getComponent("animation").toString());
managers.ObjectManager.getInstance().addObject(entity);
That is, I think you want those last few steps to be performed after the while-loop has completed, rather than doing it at the end of each iteration.

Related

alter dictionary object in local variable

I'm trying to both remove the method from the method ArrayList and check to see if the ArrayList is empty in one lookup.
This uses two look ups.
private Map<String, List<Method>> events;
public void removeEvent(String eventName, Method method){
try{
events.get(eventName).remove(method);
if(events.get(eventName).size() == 0){
events.remove(eventName);
}
}
catch (Exception e){
}
}
As you can see it looks up the ArrayList of methods to remove a method then looks it up again to see if its length is zero then looks it up again to remove the HashMap entry. Is their a way to combine at least the first two look ups?
You may change it to this way:
List<Method> methods = events.get(eventName);
if (methods == null) {
return;
}
methods.remove(method);
if (methods.isEmpty()) {
events.remove(eventName);
}
Below code might be helpful in your case.
It does not require to lookup second times to check the size of list.
public void removeEvent(String eventName, Method method){
try{
List<Method> methods = events.get(eventName);
methods.remove(method);
if(methods.size() == 0){
events.remove(eventName);
}
}
catch (Exception e){
}
}

How do I make sure that a block of code only executes ONCE and only ONCE. And NEVER AGAIN

I've tried creating a public static variable (NOT LOCAL) and purposely making an increment to it and telling Java:
"If this variable == 0, then execute this code"
so that even if that method is called the second time, that block of code won't execute because the variable has changed and is no longer zero... and it will never again be zero because it keeps increasing.
public void actionPerformed(ActionEvent e){
if(e.getSource()==deal){/*do something*/}
}
My problem is that the if statment executes more than once when I press the button "deal".
Try something like:
public class Test {
private boolean isExecuted;
public synchronized void executeOnce() {
if (isExecuted) {
return;
} else {
//do your stuff
isExecuted = true;
}
}
}
Modify it as per your requirement. To improve performance, you can use double checked locking.
Try this way, It's dummy code but through this way, you can execute inner for loop code only once.
List<WebElement> allelements = driver.findElements(By.id("id1"));
int i = 0;
for (WebElement e : allelements)
{
i++;
List<WebElement> secondelements = driver.findElements(By.id("id2"));
if(i==1)
{
for(WebElement ae : secondelements)
{
System.out.println(ae.getText());
}
}
System.out.println(e.getText());
}

Can we get the exact location where the condition fails, in an If case having multiple conditions?

I am new to Java,
Here is my code,
if( a.name == b.name
&& a.displayname == b.displayname
&& a.linkname == b.linkname
......... )
return true;
else
return false;
I will call this method and have to check that all properties of objects 'a' and 'b'.
Each object will have more than 20 properties. So, it is will be tidy if i use if case for each property.
An exception is throwed if the return is false and I have to report which property fails.
Is there any easy method to find where the condition fails within the if case.
Pls help. Ask if you are not clear about the question.
The question is, would you like to continue checking if one of the conditions fails?
You could do something like comparator where you have interface:
public interface IComparator {
boolean compare(YourObject o1, YourObject o2);
String getComparatorName();
}
Next you create set of implementations of that interface:
NameComparator implements IComparator {
private name="Name Comparator";
#Override
public boolean compare(YourObject o1, YourObjecto2) {
return o1.getName().equals(o2.getName());
}
#Override
public String getComparatorName() {
return name;
}
}
Next you store set of these comparators in arrayList and you iterate through them and record which one fails by adding them to some other collection.. Hope that helps!
For instance you create array:
IComparator[] comparators = new IComparator[]{ new NameComparator, new DisplayNameComparator};
List<IComparator> failedComparationOperations = new ArrayList<IComparator>();
for(IComparator currentComparator : comparators) {
if(!currentComparator.compare(o1, o2)) {
failedComparationOperations.add(currentComparator);
}
}
for(IComparator currentComparator: failedComparationOperations)
{
System.out.println("Failed Comparation at: "+currentComparator.getComparatorName());
}
You may use reflection: browse what fields are defined, and check each of them using method equals. Print error message if they're not equal, give summary at the end.
boolean equals = true;
Field[] fields = a.getClass().getDeclaredFields();
for (Field f: fields){
f.setAccessible(true);
try {
if (!f.get(a).equals(f.get(b))){
System.out.println(f.getName() + ": " + f.get(a) + "!="+ f.get(b));
equals = false;
};
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("equals?: " + equals);
If you need to know which of the conditions has failed you should check each of the conditions independently.
It might be a little overkill if you are dealing with this single requirement, but what about the Strategy Design Pattern?
http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism
It should be an interesting option if you have other business rules that you can combine with this check.
If a and b are instances of the same class, let's assume A, and the fields are visible, then you can use reflections:
for (Field f : A.class.getFields()) {
try {
if (!f.get(a).equals(f.get(b))) {
throw new RuntimeException("Field " + f.getName() + " is different.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Without reflection you can't get maximum conciseness, but the followincg can help you to some extent. Make this kind of class:
class NamedEquals {
final String name;
final Object left, right;
NamedCondition(String name, Object left, Object right) { ...assign them... }
boolean areEqual() { return left.equals(right); }
}
Then make a List<NamedEquals>:
List<NamedEquals> conds = Arrays.asList(
new NamedEquals("name", left.name, right.name),
new NamedEquals("displayname", left. displayname, right.displayname),
...
);
And you can find if some of them fail:
for (NamedEquals eq : conds)
if (!eq.areEqual()) throw new ValidationException(eq.name);
Using a factory method can shorten the construction code:
static NamedEquals eq(String name, Object left, Object right) {
return new NamedEquals(name, left, right);
}
With that you can have
List<NamedEquals> conds = Arrays.asList(
eq("name", left.name, right.name),
eq("displayname", left. displayname, right.displayname),
...
);
How about?
// Adapted from your example:
if(!equalTo(a.name, b.name))
fail("name");
if(!equalTo(a.displayname, b.displayname))
fail("displayname");
... etc ...
...
// Allow for null values.
public boolean equalTo(Object a, Object b) {
return a != null ? a.equals(b) : b == null;
}
public void fail(String which) throws SomeException {
throw new SomeException("Failed on '"+which+"'!");
}
Another possible might be to turn each object into a Map<String,?>, perhaps by adding a Map<String,?> toMap() method to the value object, and implementing this by constructing a new map and dumping the value's fields into it. Then you can get the maps and do equals() on them.

How to return a value from one class to another ? Java

i'm having a bit of a problem. Here's the situation. I have an amount field in my main class that gets incremented when certain buttons are clicked on. There is a method provided through which you can delete any order (I'm basically programming for a restaurant terminal) and the amount gets decremented. The delete method is placed in another class.
public void posdel(int pos, JTextField amountFieldGot, int amountGot)
{
if(slist==null)
{
JOptionPane.showMessageDialog(null, "No order has been placed yet.",null,JOptionPane.WARNING_MESSAGE);
}
else
{
if(pos==1)
{
reductionAmount = (slist.quantity*slist.price);
amountGot = amountGot - reductionAmount;
slist=slist.next;
}
else
{
int i=1;
Node temp=slist;
Node prev=null;
while(temp.next!=null && i<pos)
{
prev=temp;
temp=temp.next;
i++;
}
if(pos==i)
{
prev.next=temp.next;
}
else
{
JOptionPane.showMessageDialog(null, "Invalid order", null, JOptionPane.ERROR_MESSAGE);
}
}
}
amountFieldGot.setText(Integer.toString(amountGot));
}
So basically, I have an amountField in my GUI that i pass as a parameter to the posdel method. I also pass the amount value as a parameter. The new amount that i get is amountGot after the deletion of the first order. ( I haven't written the code for other positions.)
Suppose the amount value i pass into the method is 30 (14+16) 14 = order 1, 16 = order2.
And my first order has a value of 14.
So amountGot = 30 - 14 which is 16.
And the amountField in the GUI gets updated to 16.
Now my order 2 becomes my order 1. And if i try to delete this,
my amountField gets update to 14. (30-16 = 14).
So i'm guessing the amount value stays the same itself as 30 and does not get updated to the new amountGot value. Can someone please help me solve this problem ?
below is the code for my delete button.
deleteButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dishDelPos = JOptionPane.showInputDialog("Enter the position of the order to be deleted");
try
{
dishDeletePosition = Integer.parseInt(dishDelPos);
order1.posdel(dishDeletePosition, amountField, amount);
repaint();
}
catch(NumberFormatException ex1)
{
JOptionPane.showMessageDialog(null,"This is not a valid position");
}
}
});
A few things.
You can make the delete method in the class static. The you would reference it
value = MyClass.deleteMethod();
You can create a new class to perform the method
MyClass myClass = new MyClass();
value = myClass.deleteMethod();
You can do it using a pointer of sorts, by passing in a reference to an already existing instance of the class holding the delete method, to where you want to call it.
myFunction(MyClass myClass)
{
value = myClass.deleteMethod();
}
basically set up your function to return a value
public static int deleteMethod()
{
}
this function returns an int.
or if you need to return more than that then set the class up with global variables of information
class MyClass
{
public int value1;
public int value2;
public String value3;
public void deleteMethod()
{
//does something with global variables
}
}
now fetch the info after calling delete like so
Myclass myClass = new MyClass();
myClass.deleteMethod();
value1 = myClass.value1
value2 = myClass.Value2
value3 = myClass.Value3

What does return do when used inside an if statement?

What does the return inside the if statements do in the following code?
public void startElement(String namespaceURI, String localName,String qName,
Attributes atts) throws SAXException
{
depth++;
if (localName.equals("channel"))
{
currentstate = 0;
return;
}
if (localName.equals("image"))
{
// record our feed data - you temporarily stored it in the item :)
_feed.setTitle(_item.getTitle());
_feed.setPubDate(_item.getPubDate());
}
if (localName.equals("item"))
{
// create a new item
_item = new RSSItem();
return;
}
if (localName.equals("title"))
{
currentstate = RSS_TITLE;
return;
}
if (localName.equals("description"))
{
currentstate = RSS_DESCRIPTION;
return;
}
if (localName.equals("link"))
{
currentstate = RSS_LINK;
return;
}
if (localName.equals("category"))
{
currentstate = RSS_CATEGORY;
return;
}
if (localName.equals("pubDate"))
{
currentstate = RSS_PUBDATE;
return;
}
// if you don't explicitly handle the element, make sure you don't wind
// up erroneously storing a newline or other bogus data into one of our
// existing elements
currentstate = 0;
}
Does it takes us out of the if statement and proceeds to next statement or it takes us out of the method startElement?
The returns in the above code will take you out of the method.
It finishes the method so the code below it, is not executed.
Does it takes us out of the if statement and proceeds to next
statement or it takes us out of the method startElement?
It takes you out of the method..
The return statement terminates the execution of a function
return always takes control out of calling method.
Yes. The return here will take the control out of method.
it will return what you declared in the method head (here void = nothing = it will just end the method)
The return here is probably used in order to "improve" the performance of the method, so that other comparisons are not executed, once the needed scenario is performed.
However, it's not good practice to have multiple return points in a method.
As stated in my comments I'd try a different approach to achieve the flow of the code in question.
The return will end the flow of the method, and is functionally identical to using a shorter else if chain like
/* if (localName.equals("channel")) {
currentstate = 0; // This can be removed because it's the default below.
} else */ if (localName.equals("image")) {
// record our feed data - you temporarily stored it in the item :)
_feed.setTitle(_item.getTitle());
_feed.setPubDate(_item.getPubDate());
} else if (localName.equals("item")) {
// create a new item
_item = new RSSItem();
} else if (localName.equals("title")) {
currentstate = RSS_TITLE;
} else if (localName.equals("description")) {
currentstate = RSS_DESCRIPTION;
} else if (localName.equals("link")) {
currentstate = RSS_LINK;
} else if (localName.equals("category")) {
currentstate = RSS_CATEGORY;
} else if (localName.equals("pubDate")) {
currentstate = RSS_PUBDATE;
} else {
currentstate = 0;
}

Categories

Resources