Java中返回值的方法

Java中返回值的方法,java,eclipse,Java,Eclipse,这段代码有什么问题。在eclipse中,为什么显示该方法必须返回双精度值 public void setLength(double length){ if(length>0.0 && length<20.00){ this.length=length; }else{ dataRight=false; throw new IllegalArgumentException( "Length is not co

这段代码有什么问题。在eclipse中,为什么显示该方法必须返回双精度值

public void setLength(double length){
    if(length>0.0 && length<20.00){
        this.length=length;
    }else{
        dataRight=false;
        throw new IllegalArgumentException( "Length is not correct." );
    }
}

public double  getLength(){
    if(dataRight==false){
        System.out.printf("\nAs wrong data, calculation Not possible.\n ");
    }else{
        return length;
    }
}

因为您在此处定义了类型为double的结果值:

但在你的第一个条件下,如果你什么也不返回

至少为第一个条件返回一个默认值,如果绝对无效,则引发异常

if(dataRight==false)
        {
         System.out.printf("\nAs wrong data, calculation Not possible.\n ");
         return -1;
        }


错误在getLenght方法中

如果If语句中的条件为true,则不返回任何内容。 否则,返回一个double

因此Java编译器(而不是Eclipse)希望返回一个double

你可能想要像这样的东西

公共双getLength{ 如果dataRight==false 将新运行时异常\n作为错误数据抛出,无法进行计算。\n; 返回这个.length; }
在Java中,一个方法中每个可能的路由都必须存在一个返回路径。因此,如果任何具有返回类型的方法,使用多重选择表达式,如果它没有在方法末尾返回值,那么它必须在每个选择中返回值?抱歉,我不明白?让一个方法有三个if,返回类型为double。然后我必须从每个if块返回值,或者在方法的末尾有返回值。这是对的吗?@t否则会起作用。。。只要每个可能的路径都以return语句结尾@黑天鹅
if(dataRight==false)
        {
         System.out.printf("\nAs wrong data, calculation Not possible.\n ");
         return -1;
        }
public double  getLength() throws Exception
  {
    if(dataRight==false)
    {
     System.out.printf("\nAs wrong data, calculation Not possible.\n ");
     throw new Exception("wrong data, calculation Not possible.");
    }
    else
    {
      return length;
    }
   }
if(dataRight==false)
    {
     System.out.printf("\nAs wrong data, calculation Not possible.\n ");
    // should return from here as well or throw exception 
    }
 public double  getLength()
 {
    if(dataRight==false)
    {
       System.out.printf("\nAs wrong data, calculation Not possible.\n ");
       return 0.0; //<-- Return path must exist for all possible paths in a method, you could also add exception handling
    }
    else
       return length;
 }
public class Test {

    private double length;
    private boolean dataRight = true;

    public void setLength(double length) {
        if (length > 0.0 && length < 20.00) {
            this.length = length;
        } else {
            dataRight = false;
            throw new IllegalArgumentException("Length is not correct.");
        }
    }

    public double getLength() {
        if (!dataRight) {
            System.out.printf("\nAs wrong data, calculation Not possible.\n ");
            return 0.0; // <<<--- If dataRight is false then return double
                        // default values
        }
        return length;
    }

    public static void main(String[] args) {
        Test test= new Test();
        test.setLength(24);
        System.out.println(test.getLength());
    }
}