1

我正在用 Java 编写一个小排序程序,旨在抓取一个“学生”对象并确定它的名称、职业和课堂取决于参数和属性。然而,当我尝试创建第一个对象时,出现了一个问题。到目前为止,一切看起来像这样:

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 解释为整数,从而导致不匹配问题。

有任何想法吗?

4

2 回答 2

2

一种方法是告诉编译器该值是short使用强制转换:

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

或者,将Student类重新定义为 acceptint而不是short. (对于职业代码,我建议使用enum.)

于 2012-09-25T04:21:34.547 回答
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);
于 2012-09-25T04:44:18.380 回答