very simple boolean question (java)

Discussion in 'OT Technology' started by Pro Street, Mar 28, 2005.

  1. Pro Street

    Pro Street New Member

    Joined:
    Oct 12, 2002
    Messages:
    70,787
    Likes Received:
    0
    Location:
    Northern VA/Fucking Middle East
    why am I always getting true from this method?

    I'm trying to return true if y is a multiple of x, and false if it's not


    public class multiple
    {
    boolean answer;

    public boolean getMultiples( int x , int y )
    {
    if( x % y == 0)
    answer = true;
    else
    answer = false;

    return answer;
    }
    }
     
  2. Joe_Cool

    Joe_Cool Never trust a woman or a government. Moderator

    Joined:
    Jun 30, 2003
    Messages:
    299,223
    Likes Received:
    525
    I made answer and getMultiples static to compile, but otherwise it works perfectly as is.

    multiple.java:
    public class multiple
    {
    public static boolean answer;
    public static boolean getMultiples( int x , int y )
    {
    if( x % y == 0)
    answer = true;
    else
    answer = false;
    return answer;
    }
    }


    test.java:
    public class test
    {
    public static multiple m;
    public static void main(String args[])
    {
    boolean j;
    j=m.getMultiples(6,3);
    System.out.println(j+"\n");
    }
    }
     
  3. Joe_Cool

    Joe_Cool Never trust a woman or a government. Moderator

    Joined:
    Jun 30, 2003
    Messages:
    299,223
    Likes Received:
    525
    Oh, the way you have it will tell if x is a multiple of y, not the other way around.

    x%y returns the remainder of integer division x/y.
     
  4. Penguin Man

    Penguin Man Protect Your Digital Liberties

    Joined:
    Apr 27, 2002
    Messages:
    21,696
    Likes Received:
    0
    Location:
    Edmonton, AB
    :werd: Simple mistake, we all make those and they're fucking annoying.

    On a side note, it would be far more elegant code if you just returned y % x == 0, rather than having that if statement. Doesn't really change anything, but it looks simpler and it shows what you're doing quite clearly.
     

Share This Page