-1

I am trying to make a method that gets any field in the enclosing instance with an integer value for any "X" component for a pair of 2D coordinates (whose field name ends with "X").

    public int getX(String object) throws NullPointerException{
        String objectX = object + "X";
        Component c = null;
        try{
        Integer x = new Integer(object);
        x = c.getX();
        if(object != null){
            return x;
        }
        }catch (NullPointerException e){} // if the referenced object does not exist.
        System.err.println("The object "+object+"does not exist or the name was spelled incorrectly.");
        return (Integer)null;
    }

But all that I get in the compiler is:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input     string: "append"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.<init>(Unknown Source)
    at PlazmaBurst2.Body.getX(Body.java:118)
    at PlazmaBurst2.Body.append(Body.java:79)
    at PlazmaBurst2.Body.<init>(Body.java:53)
    at PlazmaBurst2.PB2Main$DrawingCanvas.paintComponent(PB2Main.java:40)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JLayeredPane.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paintToOffscreen(Unknown Source)
    at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
    at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
    at javax.swing.RepaintManager.paint(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at java.awt.GraphicsCallback$PaintCallback.run(Unknown Source)
    at sun.awt.SunGraphicsCallback.runOneComponent(Unknown Source)
    at sun.awt.SunGraphicsCallback.runComponents(Unknown Source)
    at java.awt.Container.paint(Unknown Source)
    at java.awt.Window.paint(Unknown Source)
    at javax.swing.RepaintManager$3.run(Unknown Source)
    at javax.swing.RepaintManager$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
    at javax.swing.RepaintManager.access$1000(Unknown Source)
    at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)    

The method would be used like this:

Image img = setImage("myImage.png");
int imgX = getX(img);// use of getX(String)

What am I doing wrong here?

AMDG
  • 1,118
  • 1
  • 13
  • 29
  • your calling getX with an int? `int ximageOffset = getX(imgx);` – corn3lius Nov 24 '13 at 02:48
  • Integer#getInteger is for named system properties: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#getInteger%28java.lang.String%29 See here for a list of them: http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html It's still not possible to do what you are wanting. – Radiodef Dec 01 '13 at 01:11
  • Closing as a duplicate by request of the original asker. Please don't ping me to argue about whether or not this is a duplicate; I have no idea. :-) – Cody Gray - on strike Aug 09 '17 at 13:05

3 Answers3

2

It seems like you think passing an object in to a String parameter as an argument passes in the object's identifier.

In other words if you do this:

public static void printObject(String ostring) {
    System.out.println(ostring);
}

Object object = new Object();
printObject(object);

Then you are thinking this will print "object" when in reality either your IDE gives you a warning because it is uncompilable or (perhaps) silently changes the code to call the object's toString method.

The way you are wanting to do this could be possible with some hacked up reflection to get any object's field "...X" but don't do that. It's hacked up.

Instead if you really want to do something "universal" like this you can use an interface that your classes implement. Interfaces are intended for this kind of thing.

// not to be confused with java.awt.Point
public interface Point {
    public Point getPoint();
    public int getX();
    public int getY();
}

Any class can implement an interface and what the methods return is up to that implementation. You can call getX on any class that implements Point and it is up to that class to decide the appropriate actions to take. Interfaces are also agnostic with regards to their implementing type.

// redundant but shows the point
public static int getXFromPoint(Point pt) {
    return pt.getX();
}

class PointImplementation implements Point {
    private Component c = somewhereElse.getAComponent();

    @Override public int getX() {
        return c.getX();
    }
    @Override public int getY() {
        return c.getY();
    }
    @Override public Point getPoint() {
        return c.getLocation();
    }
}

System.out.println(getXFromPoint(new PointImplementation()));

Not sure what you are actually wanting to return from an Image (java.awt.Image?). Why not just call the appropriate methods?

If you really want to do this in the way you are wanting to (access fields from a String?), the Java reflection tutorial covers this: http://docs.oracle.com/javase/tutorial/reflect/member/field.html

Radiodef
  • 37,180
  • 14
  • 90
  • 125
  • 1
    You can't pull a variable when it's declared only inside a constructor, even with reflection. Sorry. You'll have to rewrite your program so this kind of thing isn't necessary. That variable exists _only_ inside the constructor and _only while the constructor is being run_. – Radiodef Nov 24 '13 at 03:34
  • 1
    Like I said, you'll have to rewrite your program so it functions in a way that's possible within the rules of the language (in this case any language, local variables are irretrievable in all languages I know of). Using an array or some kind of java.util.Collection to keep track of your objects is the proper way. This falls under an XY problem: http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem Where your problem is really you need a better way of keeping track of your enemies. – Radiodef Nov 24 '13 at 04:00
0

Maybe the problem is because of the object! Is it a string containing Integer. Try to run this code that catches the NumberFormatException

  public int getX(String object) throws NullPointerException{
    String objectX = object + "X";
    Component c = null;
    try{
        try{
            Integer x = new Integer(object);
        } catch(NumberFormatException ex){
            System.out.println("You were trying to convert <" + object "> to Integer but it's impossible");
        }

        // The above line c was initiated to null so I delete this line for thest x = c.getX();
        x = (int)(Math.random() * 100) ;
        if(object != null){
            return x;
        }
    }catch (NullPointerException e){} // if the referenced object does not exist.

    System.err.println("The object "+object+"does not exist or the name was spelled incorrectly.");
    return (Integer)null;
}
puk
  • 193
  • 2
  • 13
0

It seems like you are storing the value of an object's X value in that class as a field, and you are attempting to make a method that queries the X value for that object.

The problem is that you are passing the identifier for an object to getX(String), when it actually requires a String (the name of the field?). If you want to get the value of a field, you can use reflection to get the value of a field by name:

public int getX(String object) {
    try {
        return Plasmaburst2.Body.class.getDeclaredField(object + "X");
    } catch(NoSuchFieldException | SecurityException e) {
        return 0;
    }
}

However, you may consider, for performance reasons, using a HashMap instead of reflection, or just making your own class that stores the coordinates for the object.

AMDG
  • 1,118
  • 1
  • 13
  • 29