Searching arrays?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mohaakilla51
    New Member
    • Jul 2007
    • 39

    Searching arrays?

    Is there a better way to do this:
    Code:
    // attackable[] is a array of Country objects. it is variable in length
    	public boolean canAttack(Country c) 
    	{
    		int x;
    		for(x = 0; (attackable[x] != c)&&(x < attackable.length); x++){};
    		if((x < attackable.length) && (attackable[x] == c)) 
    		{
    			if(c.getOwner() == owner)
    				return false;
    			else
    				return true;
    		} else
    			return false;
    	}
    That's a method that I'm working on for my compsci class... anyone know a more efficient way to do that? mainly just the
    Code:
    		int x;
    		for(x = 0; (attackable[x] != c)&&(x < attackable.length); x++){};
    		if((x < attackable.length) && (attackable[x] == c))
    part, but any help or pointers with the rest would be appreciated too.
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    #2
    There is a better way to do it indeed. For example, you don't have to have that for loop run without doing anything. And see, it tests the same thing as the if command beneath.

    Then, you check [code=java]if(c.getOwner() == owner) // shouldn't that be done with equals? (see below)[/code] and then return the opposite of that answer - that can be shortened a lot. Just have a look at this: [code=java]public boolean not(boolean myBoolean) {
    return !myBoolean;
    }[/code] It will always return the opposite of the boolean you gave - do you understand why?

    Also, remember that as soon as you return a value, the rest of the code will not be run. So you can leave out some tests.

    Now, isn't Country a own class? If so, you should compare it with [code=java]if(attackable[x].equals(c)) {...[/code] Similar with the owner - if that's anything but a primitive data type, you should compare that with equals too.

    Greetings,
    Nepomuk

    Comment

    • mohaakilla51
      New Member
      • Jul 2007
      • 39

      #3
      Lol, thanks :) I wrote that at like, midnight :P

      Question, do I have to write my own equals method, or does java do that automatically for me?

      Comment

      • Nepomuk
        Recognized Expert Specialist
        • Aug 2007
        • 3111

        #4
        Originally posted by mohaakilla51
        Lol, thanks :) I wrote that at like, midnight :P

        Question, do I have to write my own equals method, or does java do that automatically for me?
        You should write your own - this article should help you do so.

        Greetings,
        Nepomuk

        Comment

        Working...