jSeesFor3ver
jSeesFor3ver

Reputation: 83

Java sign of number code

I am trying to return the sign of a number using my code here but there seems to be a problem with my use of return? Help por favor?

import java.util.*;

public class ReturnTest {
    public static int sign(int n) {
        if (n > 0)
            return 1;
        else if (n == 0)
            return 0;
            else if (n < 0)
                return -1;
    }

Upvotes: 1

Views: 307

Answers (3)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

The problem is that you're not returning a method from all the paths in your method. You can see this by indenting the code accordingly based on Oracle Java Code Conventions:

public static int sign(int n) {
    if (n > 0) {
        return 1;
    } else if (n == 0) {
        return 0;
        } else if (n < 0) {
            return -1;
        }
    }
    //needs a return here...
}

This can be fixed by having a default return value at the bottom. The code may look like:

public static int sign(int n) {
    if (n > 0) {
        return 1;
    } else if (n == 0) {
        return 0;
    }
    return -1;
}

There are other ways to implement this, but I prefer to do a fix based on your current implementation.


From your comments, looks like you're in your first steps to learn Java. To make an application, you need an entry point. This is marked by the main method which has this signature:

public static void main(String[] args)

So, in your current class, you can add this method and use it to call your sign method. I'll show a very basic sample:

public class ReturnTest {
    public static int sign(int n) {
        if (n > 0) {
            return 1;
        } else if (n == 0) {
            return 0;
        }
        return -1;
    }
    public static void main(String[] args) {
        int n = 10;
        int signOfN = sign(n);
        System.out.println("The sign of " + n + " is: " + signOfN);
    }
}

It depends to you to adapt this code for your needs. I highly recommend you learn the basics. You can start here:

Upvotes: 3

Mitch Wheat
Mitch Wheat

Reputation: 300549

   public static int sign(int n) 
   {
       if (n > 0)
          return 1;
       else if (n < 0)
          return -1;

       return 0;
   }

The last if-else was unnecessary. I've re-ordered to the 'usual' way of falling through at zero. Writing the code like this is shorter, cleaner and easier to understand

Upvotes: 3

Philip Helger
Philip Helger

Reputation: 1864

Spare the last if (if (n < 0)) because otherwise there is a theoretical branch where the function is never left! Each branch must return!

Upvotes: 1

Related Questions