Results 1 to 3 of 3

Thread: JAVA if problem

  1. #1
    toby is offline Member
    Join Date
    Jul 2007
    Posts
    40
    Rep Power
    0

    Default JAVA if problem

    Hi, I am working on a JAVA if problem. Basically it checks if the number inputted is larger than 0. If it is, it does another IF statement which checks if the number is even or odd and returning 0 or 1 respectively. Either one should then return to the original IF problem but with half the n value. Here is what i done but it does not seem to work and returns errors:

    Java Code:
    static String test(int n) {
        if (n >0) 
    
        {
          if (n%2 == 0)
            return 1; n+test(n%2);
          else
            return 0; n+test(n%2);
        }
          else 
            return;
    
      }
    Thanks.

  2. #2
    cruxblack is offline Senior Member
    Join Date
    Jul 2007
    Posts
    130
    Rep Power
    0

    Default

    Java Code:
    if (n%2 == 0)
            return 1; n+test(n%2);
          else
            return 0; n+test(n%2);
    I haven't tried ur code, but if im not mistaken, if u write return, wouldn't the program got out of the if before it can even do the n+test?:confused:
    And also, i haven't tried it, but 2 statements that are written in one line are considered 2 statements after all right?
    Maybe u should use braces, just for precaution

    And btw, if u could maybe post the error message so we can figure whats wrong?
    Hope this helps

  3. #3
    Seemster is offline Member
    Join Date
    Jul 2007
    Posts
    55
    Rep Power
    0

    Default

    Exactly what the previous poster said. once it encounters return, it exits the block. your code will not compile since the code after the return is unreachable. you could split into 2 methods like this:

    public void someMethod() {
    int value = 9;

    System.out.println("the value: " + value + " is: " + determineValue(value));
    System.out.println("n is now: " + n/2);
    }

    public int determineEvenOdd(int n) {
    int returnValue = 0;

    if (n > 2) {
    returnValue = (n%2 == 0) ? 1: 0;
    }

    return returnValue;
    }

Similar Threads

  1. Problem to ToolTip in Java 3d
    By roshithmca in forum AWT / Swing
    Replies: 1
    Last Post: 02-05-2008, 04:46 AM
  2. Problem in java
    By saytri in forum New To Java
    Replies: 4
    Last Post: 01-16-2008, 11:09 PM
  3. Problem in java
    By saytri in forum New To Java
    Replies: 6
    Last Post: 01-09-2008, 05:13 PM
  4. Problem with timer in java
    By paul in forum Advanced Java
    Replies: 3
    Last Post: 07-26-2007, 11:18 AM
  5. java SE 6 problem
    By techlance in forum Java Applets
    Replies: 1
    Last Post: 06-28-2007, 11:10 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •