Jump to content
  • Advertisement
Sign in to follow this  
Nicholas Kong

Is there a shorter way that does the same thing

This topic is 1829 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

The code is actually much longer but I decided to post a small snippet to avoid posting repetitive code. The idea is that the game detects which of the 26 alphabets was pressed and does a certain action upon key press. Code is in Java.

 

    public void keyTyped(KeyEvent e) {
 
    if(e.getKeyCode() == KeyEvent.VK_A)
        {
            
        }
        else if( e.getKeyCode() == KeyEvent.VK_B)
        {
            
        }
    }
 

Share this post


Link to post
Share on other sites
Advertisement

Yes, a switch with 26 cases is perfectly fine, and it's possibly the clearest and fastest way to do it. Another valid alternative is using an array of function pointers (are there function pointers in Java?).

Share this post


Link to post
Share on other sites

Is it okay to have 26 cases using switch? Or do I just have to live with it?

 

Aside from a lookup table, using a switch statement is probably the most efficient option. The compiler might actually rewrite the switch statement to use a lookup table, but it's not required to. However, using a lookup table would require a lot of boilerplate unless the switch statement is just mapping key codes to character values, which doesn't seem to be the case, so I'd go with the switch statement unless this code became a major bottleneck (which is quite unlikely).

 

Edit:

 

Looks like Álvaro got to it before me.

Edited by BLM768

Share this post


Link to post
Share on other sites

Yes, a switch with 26 cases is perfectly fine, and it's possibly the clearest and fastest way to do it. Another valid alternative is using an array of function pointers (are there function pointers in Java?).

Java has neither pointers nor first class functions.

 

an array of objects with a suitable interface would be the closest you'd get in Java unless you use reflection. (You'd have to write one class for each mappable action though)

If you use reflection you can access a method by its name and a mapping from keycode to a string containing the method name is fairly clean but you'd get a bit of overhead on the method call itself.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!