2016-03-02 166 views
0

我創建了這個方法,我不確定它爲什麼說有一個缺少的return語句。我是否需要將印刷品更改爲退貨? (這是最底層的方法)我是一個Java初學者,所以任何幫助將不勝感激!缺少return語句方法ReturnCopy

public class Book { 
private String title; 
private String author; 
private int copies; 
private boolean borrowed; 


public Book(String inAuthor, String inTitle, int inNumberOfCopies) { 
    this.author = inAuthor; 
    this.title = inAuthor; 
    this.copies = inNumberOfCopies; 

} 

public void borrowed() { 
    borrowed = true; 
} 

public void rented() { 
    borrowed = true; 
} 

public void returned() { 
    borrowed = false; 
} 

public boolean isBorrowed() { 
    return borrowed; 
} 

public String getAuthor() { 
    return this.author; 

} 

public static String getTitle() { 
    return getTitle(); 

} 

public int getTotalCopies() { 
    return this.copies; 

} 

public int getAvailableCopies() { 

} 

public void withdrawCopy() { 
     int found = 0; 
for (Book b : Library.getListOfBooks()) { 
    if (b.getTitle().equals(title)) { 
     if (found == 0) { 
     found = 1; 
    } 
    if (!b.isBorrowed()) { 
     b.borrowed=true; 
     found = 2; 
     break;  
     } 
    if (found == 0) { 
     System.out.println("Sorry, this book is not in our catalog."); 
    } else if (found == 1) { 
     System.out.println("Sorry, this book is already borrowed."); 
    } else if (found == 2) { 
     System.out.println("You successfully borrowed " + title); 
    } 
    } 

    } 

} 

public String returnCopy() { 
    boolean found = false; 
    for (Book book : Library.getListOfBooks()) { 
     if (getTitle().equals(title) && book.isBorrowed()) { 
      book.returned(); 
      found = true; 
     } 
     if (found) { 
     System.out.println("you successfully returned " + title); 
    } 
    } 
} 
} 
+0

因爲它不是'void'方法,它必須返回一個'String'。換句話說,或將其改爲void或將其更改爲'boolean'(這似乎就是它的意思) – Maljam

回答

0

你定義的方法返回一個String,但你不要在方法身體的任何地方返回一個值。簡單的解決辦法可能是返回類型更改爲void ...

public void returnCopy() {... 

} 
1
public String returnCopy() 

Stringpublic後意味着這個方法將返回一個String。 你的public String returnCopy()目前沒有返回任何東西。

如果你不想返回任何東西,你可以用void這樣的:

public void returnCopy(){ 
    // code 
} 

同樣的問題與public int getAvailableCopies(),這應該返回int,但你不返回任何東西。

注意:

這種方法:

public static String getTitle() { 
    return getTitle(); 
} 

是一個沒有基礎條件的遞歸方法。這會導致錯誤並強制您的應用程序崩潰。

0

以上所有的答案都指向同一個問題,你已經定義了正在打破對他們返回什麼合同法..

在你的代碼,你也一樣是這樣的:

public int getAvailableCopies() { 

} 

所以你告訴編譯器,你有一個方法名爲getAvailableCopies,它需要沒有PARAMS返回一個整數

,但如果你不返回任何東西,那麼你就違背自己的方式,自己的合同,這是一個足夠的理由爲編譯器抱怨......


結論:

請記住定義方法的信息。