-2

I have encountered a problem while writing code for a small game I've been working on. In the following code I am trying to use object oriented programming. as I am using KeyEvent I think I need to use 2 methods however for some reason int key cannot be found. Can somebody help me?

    class KeyEvt {
        void keyPressed (KeyEvent e) 
        {
            int key = e.getKeyCode();
        }
    }
    class Dodger {
        public static void main (String args[])

        {
            boolean GameOver = false;
            int obst;
            KeyEvt left = new KeyEvt();

            do
            {
                obst = (int) (Math.random() * 4) +1;
                if (obst == 1)
                {
                    System.out.println("   ---");
                    if (KeyEvt.key == KeyEvent.VK_LEFT){}
                }

1 Answers1

0

In your class KeyEvt you don't declare an instance variable key, but a method variable key in keyPressed. This method variable will 'disapear' as soon as the method has finished.

In order to retain the value after the method has completed you need to declare it as an instance variable:

class KeyEvt {
    public int key;
    void keyPressed (KeyEvent e) 
    {
        key = e.getKeyCode();
    }
}

You'd also need to access an instance of the KeyEvt class, not the KeyEvt class itself:

if (left.key == KeyEvent.VK_LEFT){}

Obviously this lacks a lot of encapsulation (key is modifiable by others), and as the original KeyEvent already has the keycode the question arises why you'd need a KeyEvt class after all as the the KeyEvent class provides what you need.

M. le Rutte
  • 3,525
  • 3
  • 18
  • 31
  • better set `key` as `private` and add `getter` – shahaf Apr 14 '18 at 11:25
  • As I wrote, this lacks encapsulation at all, and the `KeyEvt` class is not necessary at all. However the current problem of the OP is the instance variable, other things will follow later :-) – M. le Rutte Apr 14 '18 at 11:28
  • Thanks a lot, your help is greatly appreciated – Luca Spiteri Apr 14 '18 at 11:39
  • Yes, probably, when glancing over the code I can see several issues. My advice would be to build your code in very small steps, not proceeding until you've got the small step running. – M. le Rutte Apr 14 '18 at 11:39