我正在用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);
}
}
错误在对象创建行上出现,因为在构造函数调用short时,它坚持将0,0解释为整数,从而导致不匹配问题。
有什么想法吗?
答案 0 :(得分:2)
一种方法是使用强制转换器告诉编译器该值为short
:
Student Andreiy = new Student("Andreiy",(short)0,(short)0);
或者,重新定义Student
课程以接受int
而不是short
。 (对于职业代码,我建议使用enum
。)
答案 1 :(得分: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);