Unreachable Statement On "Return"

708 views Asked by At

Here's My First Class:

public class Fraction
{
    int Numerator;
    int Denominator;

    /**
     * Constructor for objects of class Fraction
     */
    public Fraction()
    {
        // initialise instance variables
        Numerator=0;
        Denominator=0;        
    }

    public Fraction(int StartNumerator , int StartDenominator)
    {
        StartNumerator = Numerator;
        StartDenominator = Denominator;      
    }

    public String toString()
    {
        String FractionOne = Numerator + "/" + Denominator;
        String FractionTwo = Numerator + "/" + Denominator;

        return FractionOne;
        return FractionTwo;
    }      
}

Here's my second Class:

public class TestFraction
{
    public static void main (String [] args)
    {

        Fraction FractionOne = new Fraction(1 , 4);
        Fraction FractionTwo = new Fraction(2 , 3);

        System.out.println(FractionOne);
        System.out.println(FractionTwo);     
    }
}

When I compile, I get an error upon: return FractionTwo; as an unreachable statement

Please help me understand what I am doing wrong.

3

There are 3 answers

2
Eran On
return FractionOne;
return FractionTwo;

You can't have two return statements one after the other. The second one can never be executed, since the first one will exit the method. That's why the second statement is unreachable.

If what you want is to return both Strings, you should probably concatenate them :

return FractionOne+FractionTwo;

or

return FractionOne+","+FractionTwo;

or

return FractionOne+"\n"+FractionTwo;

However, since both of them are identical, I don't see the point in returning both.

0
StackFlowed On

The problem is you can only have one return.

If you need to send 2 values look at Java Collections API

You could do something like :

@Override
public String toString()
 {
    String FractionOne = Numerator + "/" + Denominator;
    String FractionTwo = Numerator + "/" + Denominator;
    return FractionOne + " "+ FractionTwo;
}

Please add override to the function to override toString functinoality

0
whatever5599451 On

Like everyone else has said, once you "return", no further statements can be processed.

Also, you're going to have problems with this constructor:

  public Fraction(int StartNumerator , int StartDenominator)
    {
        StartNumerator = Numerator;
        StartDenominator = Denominator;

    }

Finally, you are initializing a denominator to 0 in the default constructor. That's probably a bad idea.