2014-10-01 97 views
-2

這是我的代碼完整。我意識到它沒有完成,但我有問題的ISBN參數部分。當我編譯時,它說「不兼容類型」突出顯示「返回」不正確的ISBN「;」需要幫助 - 使用int和String的Java if/else語句

class Book{ 
    private String title; 
    private int ISBN; 
    private String authorLastName; 
    private String authorFirstName; 
    private int yearPublished; 

    public Book(){ 
    } 

    public Book(String newTitle, int newISBN, String newAuthorLastName, 
    String newAuthorFirstName, int newYearPublished){ 
     title    = newTitle; 
     ISBN    = newISBN; 
     authorLastName  = newAuthorLastName; 
     authorFirstName  = newAuthorFirstName; 
     yearPublished  = newYearPublished;  
    } 

    public String setTitle(String newTitle){  
     if(title.length()> 3){ 
     return title; 
     }else{ 
      return "Title too short."; 
     } 
    } 

    public int setISBN(int newISBN){  
     if((newISBN>=10000) &&(newISBN<=20000)){ 
      return ISBN; 
     }else{ 
      return "Incorrect ISBN"; 
     } 
    }  
} 

如果你們能我將不勝感激!

+2

你知道什麼返回類型和return語句是誰? – 2014-10-01 03:36:10

+4

爲什麼你的'set'方法沒有設置任何東西? – SLaks 2014-10-01 03:37:06

回答

3
public int setISBN(int newISBN){ 

意味着,方法返回的int的數據類型。當你這樣寫:

return "Incorrect ISBN"; 

你正在嘗試返回String。你不能那樣做。你返回一個整數。

你可能想要做的是返回一個負數,如果它是不正確的,並打印出來說明是錯的。這樣,你就知道不要使用無效號碼,但仍然會返回一個int

這樣,例如:

public int setISBN(int newISBN){  
    if((newISBN>=10000) &&(newISBN<=20000)){ 
     return ISBN; 
    }else{ 
     System.out.println("Incorrect ISBN"); // print out that it's invalid 
     return -1; // should be known that -1 means it's invalid 
    } 
} 

作爲一個說明,你set方法沒有意義。 A set方法將字段設置爲某個值。當你返回一些東西時,它應該被稱爲get方法。

0

那麼,你的函數聲明返回一個int但它返回一個字符串。這是一種類型不匹配。

您可以通過使用一個特殊的標誌值「不正確」解決這個問題,像-1或東西:

public int setISBN(int newISBN){  
    if((newISBN>=10000) &&(newISBN<=20000)){ 
     return ISBN; 
    }else{ 
     return -1; // or whatever 
    } 
} 

不過,我注意到你正在使用setISBN()驗證功能。我建議改變它返回一個boolean和重命名:

public boolean isValidIsbn(int newIsbn){  
    return ((newIsbn>=10000) &&(newIsbn<=20000)); 
} 

這將返回true如果ISBN是「有效」(由您定義)和false如果事實並非如此。

0

問題是在這裏:

public int setISBN(int newISBN){  
     if((newISBN>=10000) &&(newISBN<=20000)){ 
      return ISBN; 
     }else{ 
      return "Incorrect ISBN"; // must be int 
     } 
} 

你正在返回的功能String"Incorrect ISBN" & return typeint

所以返回somwthinh就是獨特之處在於LL識別ISBN值不10000 to 20000之間,假設回報0 &檢查有沒有價值0與否。或者更好,如果你使返回類型爲boolean。所以它會是:

public boolean setISBN(int newISBN){  
     if((newISBN>=10000) &&(newISBN<=20000)){ 
      return true; 
     }else{ 
      return false; 
     } 
} 
1

您在以下方法中返回錯誤的值(即String)。

public int setISBN(int newISBN){  
    if((newISBN>=10000) &&(newISBN<=20000)){ 
     return ISBN; 
    }else{ 
     return "Incorrect ISBN"; // Wrong 
    } 
} 

回報int,而不是作爲String

public int setISBN(int newISBN){  
    if((newISBN>=10000) &&(newISBN<=20000)){ 
     return ISBN; 
    }else{ 
     return newISBN; 
    } 
}