Okay, I'm working on a project for class, and...I can't seem to get...subtraction to work right with regards to an object in a class, let me just post the code, here's the block in the main file:

class KeyHandler extends KeyAdapter
    {
        @Override
        public void keyPressed(KeyEvent e)  
        {
            char character  = (KeyEvent.getKeyText(e.getKeyCode())).charAt(0);
            switch(character)
            {
                case 'U':
                    player.setY(player.getY() - 5);
                    //debug line
                    System.out.println(player.getY());
                case 'D':
                    player.setY(player.getY() + 5);
                    //debug line
                    System.out.println(player.getY());
                case 'L':
                    player.setX(player.getX() - 5);
                case 'R':
                    player.setX(player.getX() + 5);
                case 'Z':
                case 'X':
            }
            //udrl = updownrightleft zx = zx
           //******** Part of the framework *************
           appletPaint = false; // do not delete this statement
           repaint(); // do not delete this statement
    	}
    }

And here are the methods from the class that I use in the above:

public int getX()
    {
        return this.body.x;
    }

    public int getY()
    {
        return this.body.y;
    }

    public void setX(int x)
    {
        body.x = x;
    }

    public void setY(int y)
    {
        body.y = y;
    }

The problem is that the negative values are subtracting ONCE, but returning it's original value (150 in this case) afterward. The addition ones retain their value after the switch ends. I really have no idea what the cause of that is, to be honest.

(as a note, there is more overhead to the block there, the adding of handlers and such, but, to be blunt, the "framework" my professor made us use is...nightmarish at best, so it would take me a bit to fish out all of the code that is related to the one KeyHandler class if it would be helpful, but would rather not.)

Recommended Answers

All 2 Replies

Check out how a switch works - you haven't quite understood it properly...
http://download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
The critical sentence on that page is

The switch statement evaluates its expression, then executes all statements that follow the matching case label.

Have a look at the first example on that page. Can you see how that differs from your switch, and why (given the above quote)?

....yeah...I'm going to mark this solved now...that was kinda a bad mistake.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.