简体   繁体   English

无法获得“返回”声明

[英]Unreachable Statement On “Return”

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; 编译时,出现以下错误:return FractionTwo; as an unreachable statement 作为无法到达的陈述

Please help me understand what I am doing wrong. 请帮助我了解我在做什么错。

return FractionOne;
return FractionTwo;

You can't have two return statements one after the other. 您不能一个接一个地返回两个return语句。 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. 但是,由于它们都是相同的,所以我看不到返回两者的意义。

The problem is you can only have one return. 问题是您只能获得一次退货。

If you need to send 2 values look at Java Collections API 如果您需要发送2个值,请查看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 请在函数中添加重写以重写toString的功能

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. 最后,在默认构造函数中将分母初始化为0。 That's probably a bad idea. 那可能是个坏主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM