簡體   English   中英

Java中返回值的方法

[英]method returning value in Java

這段代碼有什么問題? 在Eclipse中,為什么顯示該方法必須返回一個double值?

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類型的結果值:

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

但在您的第一個if condition您什么也不返回。

返回第一個condition至少一個默認值,或者如果絕對無效則拋出exception

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 
    }

錯誤發生在getLenght()方法中。

如果if語句中的條件為true,則不返回任何內容。 否則,您將返回一個雙精度值。

因此,Java編譯器(不是Eclipse)期望返回一個double。

您可能想要類似

public double getLength() {
    if( dataRight == false )
        throw new RuntimeException("\nAs wrong data, calculation Not possible.\n ");
    return this.length;
}
 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());
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM