2012-09-25 66 views
1

我在Java中編寫了一個小的排序程序,旨在獲取「學生」對象並確定其名稱,職業和課堂是依賴於參數和屬性。然而,當我嘗試創建第一個對象時,出現了一個問題。 迄今爲止,一切看起來是這樣的:Java構造函數:創建一個對象,短參數被解釋爲int

public class Student { 
    private String name, classroom; 
    /** 
    * The career code is as follows, and I quote: 
    * 0 - Computer Science 
    * 1 - Mathematics 
    * 2 - Physics 
    * 3 - Biology 
    */ 
    private short career, idNumber; 

    public Student (String name, short career, short idNumber){ 
     this.name = name; 
     this.classroom = "none"; 
     this.career = career; 
     this.idNumber = idNumber; 
    } 

    public static void main(String args[]){ 
     Student Andreiy = new Student("Andreiy",0,0); 
    } 
} 

錯誤變成了對對象的創建行,因爲由於某種原因,堅持解釋0,0爲整數時,構造函數調用短褲,導致不匹配問題。

任何想法?

+0

你能後的異常或錯誤的詳細信息? 'new Student(「Andreiy」,(short)0,(short)0);'或者在你的短號後面寫's':'new Student(「Andreiy」,0s,0s) – Dai

+0

;' –

+0

http://stackoverflow.com/questions/477750/primitive-type-short-casting-in-java?rq=1 related – jozefg

回答

2

的一種方法是,告訴該值是short使用強制編譯:

Student Andreiy = new Student("Andreiy",(short)0,(short)0); 

或者,重新定義Student類接受int,而不是short。 (對於職業代碼,我建議使用enum。)

0

您應該將Integer轉換爲short。整數縮短轉換需要縮小,因此需要顯式轉換。只要你有內存限制,你應該在java中使用整數。

public Student (String name, Career career, int idNumber) 

//Enumeration for Career so no additional checks are required. 
enum Career 
{ 
    Computer_Science(0),Mathematics(1),Physics(2),Biology(3); 
    private Career(int code) 
    { 
     this.code = code; 
    } 
    int code ; 

    public int getCode() 
    { 
     return code; 
    } 

} 

然後你就可以做類似下面

new Student("Andreiy", Career.Computer_Science, 0); 
相關問題